javascript/typescript – force to pass object as function argument by eslint rule

Is it possible to force the following rule by eslint?

  • if the number of function arguments is more than one, use “object” as an argument.

For example,

  • good
    • const f = (x: string) => …
    • const f = (x: {id: string}) => …
    • const f = (x: {id: string; name: string}) => …
  • bad
    • const f= (x: string; y: string) => …

I checked the official document ( https://eslint.org/docs/rules/ ), but I couldn’t find appropriate rules.
I wonder if some kind of custom rules can realize this.

Why is javascript does this behaviour when using and not using slice() method? [duplicate]

I was solving a probelm using javascript when i found out this strange behaviour of javascript when using and when not using slice() mthod. I don’t know if this behaviour is strange only to me or what, i googled it but couldn’t help myself to clear confusion.

Here is an example to illustrate strage behaviour, atleast according to me (i guess):

const arr1 = [1, 2, 3];
const arr2 = arr1;
console.log(arr2);
arr2.splice(1, 0, 1);
console.log(arr2);
console.log(arr1);

According to this the output is :

[ 1, 2, 3 ]
[ 1, 1, 2, 3 ]
[ 1, 1, 2, 3 ]

The value of variable arr1 also changes althoughi didnt assign any changes to this variable. I guess it is some sort my mutating from new variable or what i don’t know.

But when is use slice() method to copy value to another variable:
The code be like this

const arr1 = [1, 2, 3];
const arr2 = arr1.slice();
console.log(arr2);
arr2.splice(1, 0, 1);
console.log(arr2);
console.log(arr1);

The output comes like this

[ 1, 2, 3 ]
[ 1, 1, 2, 3 ]
[ 1, 2, 3 ]

Now the value doesn’t change which was required to solve my problem.
Why this happens when not using slice and what does slice do to prevent it?
Please help me.

Element doesn’t add a class until certain code has executed, but I want it to do it before

I made a simple program in js that changes the aspect ratio of user uploaded images,I know that this is probably not the best way to do this sort of thing, but I think of it as practice.Here’s the repo, and here’s a live version.

There’s a div with class .loading-screen that is supposed to cover the entire screen while the images are being processed, that div is initially hidden with a simple class that has a
property of display : none;.

Once the user presses the “process” button for resizing the images, I try to remove the .hidden class from .loading-screen, but it doesn’t remove it, it goes straight into processing the images, and once it’s done it actually removes the class, but once the images have been finished processing, I add the class back again, so it’s added and then removed immediately after. The basic flow relevant parts of the program is as follows :

const input = document.querySelector(".file-input");
const processButton = document.querySelector(".process");
let imageDivs = [];

input.addEventListener("change", () => {
  //load the images into the program, and store 
  //the resulting divs with images inside of the
  //imageDivs array
});

processButton.addEventListener("click", () => {
  const loadingScreen = document.querySelector(".loading-screen"); //this is the div that I want to cover the screen with

  loadingScreen.classList.remove("hidden"); //remove the '.hidden' class, so that it will cover the entire window

  let promises = [];
  
  for (let div of imageDivs) {
    let img = div.querySelector("img");

    //fit_image() draws the image in a canvas, and then 
    //returns a promise that resolves to the base64 data
    //of the canvas
    promises.push(fit_image(img));
  }

  Promise.all(promises).then(values => {
    loadingScreen.classList.add("hidden"); //hide this div once we are done processing the images

    //load the resized images into the program, etc...
  });
});

The problem is that loadingScreen.classList.remove("hidden") seems to run after the images have finished being processed, because if I remove the loadingScreen.classList.add("hidden") inside of the Promises.all() statement, the loadingScreen div appears after the images are done. How do I make it load the class before the images start processing?

Unable to get data attribute value in jquery using PHP

I am working with Jquery and php,I have text box and i am trying to pass
“data attribute” (data-vals) value using jquery but i am getting “undefined” as response,
Here is my code,Where i am wrong ?

<input type='text' name='postcmnt' class='postcmnt' value='" + str + "' data-vals='123' onkeydown='search(this)' />
<script>
function search(ele) {
    if(event.key === 'Enter') {
            var valss=$(this).data('vals');
            alert('attribute value is '+valss); 
    }
}
</script>

Div not getting converted to a blob rather showing – Failed to execute ‘createObjectURL’ on ‘URL’: Overload resolution failed

I have a button with an onclick event which should convert a div containing some text and image into blob and then download it as an image.

But I am facing this issue. Help is much appreciated.
My React code

`  const download = () => {
    domtoimage.toBlob(document.getElementById("box")).then(function (blob) {
      console.log(blob);
      window.saveAs(blob, "myMeme.png");
    });
  };` 

enter image description here

throwing UnhandledPromiseRejection even the code wrapped in try catch

I am getting UnhandledPromiseRejection error even I wrapped the code in try catch block
I using await Prmomise.all together here

const express = require('express');
const app = express();
const port = 3003;

function testPromise(n) {
    return new Promise(async (res, rej) => {
        console.log(n);
        if (n > 10) {
            res(true);
        } else {
            setTimeout(() => {
                rej(n);;
            }, 1000)

        }
    });
}

function test2(n) {
    return new Promise(async (res, rej) => {
        console.log(n);
        if (n > 10) {
            res(true);
        } else {
            setTimeout(() => {
                rej(n);;
            }, 10000)

        }
    });
}
async function allCall(p) {
    await Promise.all(p);
}
app.get('/', async (req, res) => {
    try {
        let a = [];
        let b = [];

        a.push(testPromise(1));
        await test2(1);
        a.push(testPromise(12));
        // await Promise.all(a.map(m => m.then(() => { }).catch(err => { })));
        await Promise.all(a);
        res.send('Hello World!');
    } catch (err) {
        console.log('err');
        console.log(err);
        res.status(400).send('xxxxxxxxxx!')
    }

})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

I am not sure why it is throwing the error

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise
which was not handled with .catch().

Please explain why and how to resolve this ?

Unsure if this implementation of insertion sort is correct?

I found this implementation of insertion sort that avoids using the typical while loop that I’ve seen across most video explanations. I’m not exactly sure if this is valid though. Wouldn’t this be nearly identical to bubble sort? Would there really be any specific benefit of using this? Here are my implementations of insertion sort and bubble sort:

let arr = [1, 4, 6, 7, 8, 6, 3, 4, 5, 6, 6, 7];

const bubbleSort = (array) => {
  for (let i = array.length; i > 0; i--) {
    for (let j = 0; j < i; j++) {
      if (array[j] > array[j + 1])
        [array[j], array[j + 1]] = [array[j + 1], array[j]];
    }
  }
};

const insertSort = (array) => {
  for (let i = 1; i < array.length; i++) {
    for (let j = i; j > 0; j--) {
      if (array[j] < array[j - 1])
        [array[j - 1], array[j]] = [array[j], array[j - 1]];
    }
  }
};


RegExp for expression sourrounded by special characters

Is there a way to use RegExp to replace a substring surrounded by ‘/*’ on the left, and ‘*/’ on the right. The substring can include anything (numbers, underscore, special characters)

var string = "abc /*abcd_^&^djh:*/ <-abcd_.";

function replace(string, regexp, replacement="") {
    return string.replaceAll(new RegExp(regexp), replacement);
}

let regexpReplacement; //The RegExp for a substring surounded by "/*" and "*/"

console.log(replace(string, regexpReplacement));
//Should output "abc  <-abcd_."

how to filter data in array javascript

i have data json like this

[
    {
        "bulan": 1,
        "tahun": 2021,
        "total": 200
    },
    {
        "bulan": 2,
        "tahun": 2021,
        "total": 300
    },
    {
        "bulan": 1,
        "tahun": 2022,
        "total": 48
    },
    {
        "bulan": 2,
        "tahun": 2022,
        "total": 899
    },
]

how to make a filter where i only want to show data which has year 2022 only

thanks.

Issue with conditionally rendering plyr-react media from json error

Trying to conditionally render different media (aud/vid) from a json file in react but getting errors. Here is the code

{surgeryData.map((data) => (
          <div>
           
<Plyr
                    source={
                      type = {data.type},
                      sources = [
                        {
                          src= {data.media}
                        }
                      ]
                    }
                  />

          </div>
        ))}

Whether I use “=” after source or “:” react doesn’t seem to like the nested data inside the source. Any solutions? Thanks in advance.

Lodash _.isEquals method returns true even the comparing two objects are equal

I am trying to compare two objects with Lodash. One is getting as input and the other one is from db.Below is my method.


    console.log(`isDataChanged - fromDbData : ${JSON.stringify(fromDbData)}`);
    console.log(`isDataChanged - inputData : ${JSON.stringify(inputData)}`);

    if(_.isEqual(fromDbData, inputData)){
        console.log("isDataChanged - equal data found");
        return false;
    }else{
        console.log("isDataChanged - different data found");
        return true;
    }

};

the object is looks like below

{
...
"data": {
    "type": "Date",
    "name": "test",
    "tag": "sample",
    "category": null,
    "time": null,
    "caption": "the caption",
    "value": "none"
}
}

As the input parameter i’m sending the data property of both objects.
So when the values inside the data object for both I am expecting false. But it’s returning true.
Can someone please help me to understand what’s happening here?
Thanks!

Subtracting seconds from the time in Javascript

I need to create a second function that will subtract recorded time from this in seconds. Currently, this function will display time as event_time: 02:24:25 which is great, I just need to take my recorded time in seconds e.g. 85 seconds and subtract from this value.

so if DateTimeFun is 02:24:25 and recordedTime = 60, the new function would return 02:23:25, subtracting 1 minute.

let recordedTime = parseInt(inputData.new_value) - parseInt(inputData.previous_value);

let dateTimeFun = function (d) {
    let h = d.getHours();
    let m = d.getMinutes();
    let s = d.getSeconds();

    if (h < 10) h = '0' + h;
    if (m < 10) m = '0' + m;
    if (s < 10) s = '0' + s;

    return h + ':' + m + ':' + s;
}

Javascript Boolean check [duplicate]

I have a list of boolean

let x = [true,false,false,true,false]

I want to return true if at least 1 items is true

i.e. returns a value of false if every value is false

let y = [false,false,false,false,false] // should return false

I can’t seem to understand the use of array.every(function) to return false. It seems simple but I can’t figure the logic