Home > other >  How to calculate or interpret before function body?
How to calculate or interpret before function body?

Time:01-02

const isSquare = (n) => {
    const s = Math.sqrt(n)
    return s === parseInt(s)
}
console.log(isSquare(4))

To the above code, I want to write in one line something like:

const isSquare = (n) => (s = Math.sqrt(n)) => s === parseInt(s)

But it returns a function as it's currying over. Is there something better to achieve this? So that we can save the value in a variable and use it later on.


PS:

We can just use the below code to find out perfect square number.

const isSquare = (n) => Math.sqrt(n) % 1 === 0

CodePudding user response:

We can use spread syntax like this:

const isSquare = (n, ...{s = Math.sqrt(n)}) => parseInt(s) === s
console.log(isSquare(4))

CodePudding user response:

This probably isn't as good as your own answer but I've seen others use an IIFE for something like that before (if I've understood the question):

const isSquare = (n) => ((s) => s === parseInt(s))(Math.sqrt(n));
console.log(isSquare(4));

  • Related