I have a time array I want to group by on another key value having start time and end time using typescript

Time_Array = ["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00"]

Input = [
{
“hour”: “00:00”,
“gID”: 10
},
{
“hour”: “01:00”,
“gID”: 10
},{
“hour”: “02:00”,
“gID”: 10
},{
“hour”: “07:00”,
“gID”: 30
},{
“hour”: “08:00”,
“gID”: 32
},{
“hour”: “11:00”,
“gID”: 40
},{
“hour”: “12:00”,
“gID”: 40
},{
“hour”: “15:00”,
“gID”: 55
},
{
“hour”: “17:00”,
“gID”: 59
},
]

Expected_Output = [{“start_time” : “00:00”, “end_time”:”03:00″, “gID”:10},{“start_time” : “07:00”, “end_time”:”08:00″, “gID”:30},{“start_time” : “08:00”, “end_time”:”09:00″, “gID”:32}
{“start_time” : “11:00”, “end_time”:”13:00″, “gID”:40},{“start_time” : “15:00”, “end_time”:”16:00″, “gID”:55},{“start_time” : “17:00”, “end_time”:”18:00″, “gID”:59}]

Generate a const typed object in TypeScript

I am trying to generate a const typed object by passing in a string I want to use as the type, is this possible, I have tried the below and it’s bringing out the wrong type.

const test = <T> (name: T) => {
  const hi: { name: T } = {
    name
  } as const
  return hi
}

const test1 = test('hello')

I’d like this to be of type

{
    name: 'hello';
}

But instead it’s of type

{
    name: string;
}

Convert first letter of a string to uppercase

I have this code where the input of first-name last-name will be converted to lowercase then the first letters of each word will be converted to uppercase and then swap place.

However, I ran into an inconvenience where special characters(not certain with the term) were not being processed.

Input: oNdřej rasZka
Desired output: Raszka,Ondřej
What I’m getting: OndŘEj Raszka

The “ŘE” of OndŘEj was not processed properly same with other available special characters, is there any way to solve this?

<div>
  <textarea cols="50" rows="5" id="fullName" class= ""></textarea>
</div>

<button id="splitName">Click</button>
<div>
  <br>
</div>
<div class= "border" id="result"></div>

var splitName = document.getElementById("splitName");

splitName.onclick = function() {
  document.getElementById("result").innerHTML = '';

        var value = document.getElementById("fullName").value;
  
  
  //CASE CONVERT//
            var value2 = value.toLowerCase();
            value2 = value2.replace(/b./g, function(m){ return m.toUpperCase(); });

        

    value2.split('n').forEach(fullname => {
    var spaceIndex = fullname.indexOf(" ");
    var firstname;
    var lastname;
    if (spaceIndex == -1) {
      lastname = fullname;
      lastname = "";
    } else {
      firstname = fullname.substring(0, spaceIndex);
      lastname = fullname.substr(spaceIndex + 1);       
    }

        document.getElementById("result").innerHTML += lastname + " " + firstname+ "<br>";
             


  });
};

Thanks a lot.

How to sum a array like a Excel Pivot where two keys must macht?

I try to sum all “Menge” and “Fehler” values where “Datum” AND “Material” must match. The result should look like an Excel Pivot.

This is my code so far, but I don’t know how to add the second key “Material” that also must match .
I hope you can understand what I try to explain.

var arr = [{
  "Datum": {
    "date": "2000-01-01 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "123",
  "Menge": 100,
  "Fehler": 5
}, {
  "Datum": {
    "date": "2000-01-01 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "123",
  "Menge": 5,
  "Fehler": 1
}, {
  "Datum": {
    "date": "2000-01-01 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "123",
  "Menge": 6,
  "Fehler": 65
}, {
  "Datum": {
    "date": "2000-01-01 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "222",
  "Menge": 10,
  "Fehler": 5
}, {
  "Datum": {
    "date": "2000-01-02 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "444",
  "Menge": 29,
  "Fehler": 1
}, {
  "Datum": {
    "date": "2000-01-02 00:00:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/Berlin"
  },
  "Material": "123",
  "Menge": 1,
  "Fehler": 1
}]

const result = Object.values(arr.reduce((acc, obj) => {
  const [Datum] = obj.Datum.date.split(' ');
  const Menge = (acc[Datum] ?.Menge + obj.Menge) || obj.Menge;
  const Fehler = (acc[Datum] ?.Fehler + obj.Fehler) || obj.Fehler;
  acc[Datum] = {
    Datum,
    Menge,
    Fehler
  };
  return acc;
}, {}));

console.log(result)

But the result should look like:

[{
    "Datum": "2000-01-01",
    "Material": "123",
    "Menge": 111,
    "Fehler": 71
  },
  {
    "Datum": "2000-01-01",
    "Material": "222",
    "Menge": 10,
    "Fehler": 5
  },
  {
    "Datum": "2000-01-02",
    "Material": "444",
    "Menge": 29,
    "Fehler": 1
  },
  {
    "Datum": "2000-01-02",
    "Material": "123",
    "Menge": 1,
    "Fehler": 1
  }
]

Thank you very much

How to set cookie expiry age and path in Javascript? [duplicate]

I am making Cookie Consent for website and the only problem I have right now is that Cookie is stored in that session only, and I also want to set path to my root domain.
Currently my JS is like this:

const cookieStorage = {
    getItem: (item) => {
        const cookies = document.cookie
            .split(';')
            .map(cookie => cookie.split('='))
            .reduce((acc, [key, value]) => ({ ...acc, [key.trim()]: value }), {});
        return cookies[item];
    },
    setItem: (item, value) => {
        document.cookie = `${item}=${value};`
    }
}

const storageType = cookieStorage;
const consentPropertyName = 'Cookie By: RohanPhuyal ';
const shouldShowPopup = () => !storageType.getItem(consentPropertyName);
const saveToStorage = () => storageType.setItem(consentPropertyName, true);

window.onload = () => {

    const acceptFn = event => {
        saveToStorage(storageType);
        consentPopup.classList.add('hidden');
    }
    const consentPopup = document.getElementById('consent-popup');
    const acceptBtn = document.getElementById('accept');
    acceptBtn.addEventListener('click', acceptFn);

    if (shouldShowPopup(storageType)) {
        setTimeout(() => {
            consentPopup.classList.remove('hidden');
        }, 1000);
    }

};

How can I add expiry time (age) on cookie and also set path=/ ?

How to restrict date of Birth from selecting future date

<script type="text/javascript">

 //Create references to the dropdown's
const yearSelect = document.getElementById("year");
const monthSelect = document.getElementById("month");
const daySelect = document.getElementById("day");

const months = ['January', 'February', 'March', 'April', 
'May', 'June', 'July', 'August', 'September', 'October',
'November', 'December'];

//Months are always the same
(function populateMonths(){
    for(let i = 0; i < months.length; i++){
        const option = document.createElement('option');
        option.textContent = months[i];
        monthSelect.appendChild(option);
    }
    monthSelect.value = "January";
})();

let previousDay;

function populateDays(month){
    //Delete all of the children of the day dropdown
    //if they do exist
    while(daySelect.firstChild){
        daySelect.removeChild(daySelect.firstChild);
    }
    //Holds the number of days in the month
    let dayNum;
    //Get the current year
    let year = yearSelect.value;

    if(month === 'January' || month === 'March' || 
    month === 'May' || month === 'July' || month === 'August' 
    || month === 'October' || month === 'December') {
        dayNum = 31;
    } else if(month === 'April' || month === 'June' 
    || month === 'September' || month === 'November') {
        dayNum = 30;
    }else{
        //Check for a leap year
        if(new Date(year, 1, 29).getMonth() === 1){
            dayNum = 29;
        }else{
            dayNum = 28;
        }
    }
    //Insert the correct days into the day <select>
    for(let i = 1; i <= dayNum; i++){
        const option = document.createElement("option");
        option.textContent = i;
        daySelect.appendChild(option);
    }
    if(previousDay){
        daySelect.value = previousDay;
        if(daySelect.value === ""){
            daySelect.value = previousDay - 1;
        }
        if(daySelect.value === ""){
            daySelect.value = previousDay - 2;
        }
        if(daySelect.value === ""){
            daySelect.value = previousDay - 3;
        }
    }
}

function populateYears(){
    //Get the current year as a number
    let year = new Date().getFullYear();
    //Make the previous 100 years be an option
    for(let i = 0; i < 101; i++){
        const option = document.createElement("option");
        option.textContent = year - i;
        yearSelect.appendChild(option);
    }
}

populateDays(monthSelect.value);
populateYears();

yearSelect.onchange = function() {
    populateDays(monthSelect.value);
}
monthSelect.onchange = function() {
    populateDays(monthSelect.value);
}
daySelect.onchange = function() {
    previousDay = daySelect.value;
}

//Create references to the dropdown’s
const yearSelect = document.getElementById(“year”);
const monthSelect = document.getElementById(“month”);
const daySelect = document.getElementById(“day”);

const months = [‘January’, ‘February’, ‘March’, ‘April’,
‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’,
‘November’, ‘December’];

//Months are always the same
(function populateMonths(){
for(let i = 0; i
for(let i = 1; i

Checking if date is valid in javascript get `RangeError: Invalid time value` testing it

I created this function to check if the date is valid or not:

function isValidDate(dateObject){
  if(!dateObject) return;
  
    return new Date(dateObject).toString() !== 'Invalid Date';
}
console.log(isValidDate('not valid time')) // false

This function works good, but trying to test it with jest i get this error: RangeError: Invalid time value, i suppose that this happens because the argument is a string and it pass the if(!dateObject) return;.
Question: How to avoid this error in my case?

Can’t redirect to url by javascript function

I need a button, which lead up in url path like this:

from /host/elements/1
to /host/elements

I have a link in my html:

<a href="javascript:go_backward()"> </a>

And a javascript function:

function go_backward() {
    var url = window.location.href;
    var page = url.substring(0, url.lastIndexOf('/'))
    window.location.assign(page);
    return false;
}

But when i click the button i only get desired url printed, without correct redirect.
Why cat it be so?

jquery – get a value in mix radio button

Would you like to check what wrong in my code, I have 2 group radio button when I click the radio button variable r not have a value :

<script>
$(document).ready(function() {
    var s = 0;
    var l = 0;
    var r = 0;

    $('input[type=radio][name="saverity"]').change(function() {
        s = $(this).val();
        console.log(s);
    });

    $('input[type=radio][name="likehood"]').change(function() {
        l = $(this).val();
        console.log(l);
    });

    r = s * l;
    console.log(r);

});

Thank you very much.

Variable not being passed from front end to backend

I’m scratching my head at this problem, I’m implementing Instagrams basic display API using Wix’s new editor-x. My code works if I run it on the client side, I get an access token, however it doesn’t when I import the getAccessToken function from the server side, the function runs but I get an invalid auth code.

I think there maybe an issue passing the code variable?

frontend code:

import wixLocation from 'wix-location'
import {getAccessToken} from 'backend/instagram'
let query = wixLocation.query; //get auth code from URL param
    let code = query.code
    console.log(code) //check code is correct
    if(code){
        const token = await getAccessToken(code) //request accesstoken
        console.log(token) //log token
        }

backend code:

import {fetch} from 'wix-fetch'
export async function getAccessToken(code) {
    const url = "https://api.instagram.com/oauth/access_token"
    const options = {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: `client_id=id&client_secret=secret&grant_type=authorization_code&redirect_uri=uri&code=${code}`
    }
    try {
        const data = await fetch(url,options)
        const token = await data.json()
        return token
    } catch(error) {
        return error
    }
}

Using zxing Barcode Scanner within a web page and scan multiple barcodes in same page

I’m trying to use the code below to scan multiple barcodes and insert them in the coresponding textboxes. What i want to achieve is to press the scan button in front of the textfield and the scan result to be inserted in the textfield near the scanbutton.
Ex of code that i use ( is ok for the first textfield)

<!DOCTYPE html>
<script type="text/javascript">
    function zxinglistener(e){
        localStorage["zxingbarcode"] = "";
        if(e.url.split("#")[0] == window.location.href){
            window.focus();
            processBarcode(decodeURIComponent(e.newValue));
        }
        window.removeEventListener("storage", zxinglistener, false);
    }
    if(window.location.hash != ""){
        localStorage["zxingbarcode"] = window.location.hash.substr(1);
        self.close();
        window.location.href="about:blank";//In case self.close is disabled
    }else{
        window.addEventListener("hashchange", function(e){
            window.removeEventListener("storage", zxinglistener, false);
            var hash = window.location.hash.substr(1);
            if (hash != "") {
                window.location.hash = "";
                processBarcode(decodeURIComponent(hash));
            }
        }, false);
    }
    function getScan(){
        var href = window.location.href.split("#")[0];
        window.addEventListener("storage", zxinglistener, false);
        zxingWindow = window.open("zxing://scan/?ret=" + encodeURIComponent(href + "#{CODE}"),'_self');
    }

</script>

<html>
    <head>
        <script type="text/javascript">
             function processBarcode(b){
               document.getElementById("result1").value=b;

       
                 } 
        </script>
    </head>
    <body>
        <button onclick="getScan()">get Scan result1</button>
        <input id="result1"  type="text"></input><br>
        <button onclick="getScan()">get Scan result2</button>
        <input id="result2"  type="text"></input><br>
        <button onclick="getScan()">get Scan result3</button>
        <input id="result3"  type="text"></input><br>

    </body>
</html>
    

How to prevent multiple window with url https://twitter.com/i/oauth2/authorize

I’m opening a new window with url https://twitter.com/i/oauth2/authorize?scope=tweet.read%20users.read%20follows.read%20follows.write&state=state&client_id=clientID&response_type=code&code_challenge=789089&code_challenge_method=plain&redirect_uri=http://localhost:4200/app/callback

But, when the url is loaded in new window, the popupWindow.closed property is getting set to true. Hence, leading to multiple windows getting open on button click. This doesn’t happen with linkedin’s oauth url

if (this.popupWindow == null || this.popupWindow.closed) {
      this.popupWindow = window.open(
        `${authUrl}?${params}`,
        'twitter',
        `menubar=no,location=no,resizable=no,scrollbars=no,status=no,toolbar=no, width=${width},height=${height},top=${top},left=${left}`
      );
    } else {
      this.popupWindow.focus();
    }

How do i prevent multiple window from opening?

Print out these counted values

I need answer ASAP
Given a set of five numbers that include both positive and negative data values. Create a program to read in these values one at a time and count the number of positive values (including zero) and the number of negative values found in the set. Print out these counted values.

Example:

Set of values: 1, -1, 0, 2, 4

Negative: 1

Positive: 4

Can I use uncontrolled inputs in React without ref?

I’ve a complex form (with over than 70 inputs) and it has many different inputs and children forms… I’ve decided to add a from tag then repeat all inputs inside that:

<form>
  <input name="email" />
  <input name="age" />
  <input name="address" />
  .
  .
  .
  { loop on state (Array) to render other re-usable form component for category or city etc. }
  { another loop on state (Array) to render file inputs and checkboxes etc. }
  .
  .
  .
</form>

I actually should get an API data then generate that form to collect data from user (we haven’t a fixed and common form, it depends on client and many things…). After that, I decided to forget controlled inputs, because I’ve to make a spaghetti and complex component to handle many states for this situation, I decided to use something like Formik, but that’s not really easy! because I’ve to pass many API methods to handle custom inputs onChange values…

Therefore, I’ve decided to get form values by onSubmit event (without ref):

const handleSubmit = (e) => {
  e.preventDefault();
  const values = new FormData(e.target);
  sendForm(values); // sending form by post method and formData
}

<form onSubmit={handleSubmit}>
.
.
.
</form>

But I’ve an important question, does effect uncontrolled input on React performance? or it’s not best practice and I’ve to find a solution to implement form by controlled inputs?