How to achieve the below logic in JS
Example:
Let y = alertMyPreviousParam(“1”);
Let z= y(‘2’)
// show output as 1
Let a = z(‘3’)
// show output as 2
Let b = a(‘ra’)
// show output as 3
Let c = b(‘z’)
// show output as ‘ra’,
Despite of various Syntax error
1) string enclosed by ‘ and ’ is not valid javascript string, similarly with “ and ”. Use either " or '.
2) variable should be declared with let not Let.
SOLUTION
You can take advantage of closure and Higher order function(HOF) here
function alertMyPreviousParam(arg) {
let last = arg;
return function (curr) {
console.log(last);
last = curr;
return alertMyPreviousParam(curr);
};
}
let y = alertMyPreviousParam("1");
let z = y("2");
// show output as 1
let a = z("3");
// show output as 2
let b = a("ra");
// show output as 3
let c = b("z");
// show output as ‘ra’,
You’ll want to look into closures. Here’s an example:
let var = null
let next = null
const myFunc = (newnext) => {
var = next
next = newnext
return var
}
Sorry for the formatting, I’m on mobile
the function alertMyPreviousParam, returns a new function, and outputs the previous input. This can be achieved as follows:
let alertMyPreviousParam = (x) => (y) => {
console.log(x);
return alertMyPreviousParam(y);
}