here is my code problem, There are three arguments in my function x, y
and num
. num
must be multiplied with x
and y
and return.
function abc(num, x, y) { return num * x + " " + num * y; } console.log( abc(5, 2, 4) //returns 10 20 ); console.log( abc(5, abc(5, 6, 6), 4) //doesn't return 30 30 20 ) function abc1(num, x, y) { if (isNaN(x)) { return x + " " + y * num; //now it returns 30 30 20 for abc(5,abc(5,6,6),4) } return num * x + " " + num * y; } console.log( abc1(5, 2, 4) //returns 10 20 ); console.log( abc1(5, abc(5, 6, 6), 4) //now it returns 30 30 20 for abc(5,abc(5,6,6),4) )
I also want to know how to achieve if I call the function below (function inside the argument of the same function)-
abc(5,abc(abc(5,abc(5,6,6),abc(5,abc(5,6,6),4)))) // it must return something like how abc(5,abc(5,6,6),4) should return 30 30 20
I want when I call the function abc(5,2,abc(5,abc(5,4,4),3))
should return all parameters(except num
) every time like 10 20 20 15
for calling the function - abc(5,2,abc(5,abc(5,4,4),3))
if I place the same function in the function Parameter/arguments.
I tried but when I call the function inside the same function arguments like abc(5,abc(5,6,6),4)
the x
in the function abc(num,x,y)
becomes NaN
hence returns like NaN 20
but not 30 30 20
.
but how to do for this abc(5,abc(abc(5,abc(5,6,6),abc(5,abc(5,6,6),4))))
to return the same way like above.
Any online source would help, Thanks.
You could return an array and check if the value is an array and use the values instead of multiplying with the given factor.
function fn(f, a, b) { return [...(Array.isArray(a)? a: [f * a]), ...(Array.isArray(b)? b: [f * b]), ]; } console.log(...fn(5, 6, 6)); // [30, 30] console.log(...fn(5, fn(5, 6, 6), 4)); // [30, 30, 20] console.log(...fn(5, 2, fn(5, fn(5, 4, 4), 3))); // [10, 20, 20, 15]
An even shorter approach
function fn(f, ...values) { return values.flatMap(x => Array.isArray(x)? x: [f * x]); } console.log(...fn(5, 6, 6)); // [30, 30] console.log(...fn(5, fn(5, 6, 6), 4)); // [30, 30, 20] console.log(...fn(5, 2, fn(5, fn(5, 4, 4), 3))); // [10, 20, 20, 15]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.