I am trying to write a boolean currying function in javascript.
JavaScript
x
16
16
1
let s = "ajkjxa";
2
3
function isPresent(a) {
4
5
return function (b) {
6
7
if (b) {
8
return isPresent(s.includes(b) && s.includes(a));
9
} else {
10
return s.includes(a);
11
}
12
};
13
}
14
15
console.log(isPresent("a")("j")("x")());//true expected
16
console.log(isPresent("a")("j")("x")('b')());//false expected
I want isPresent function should return true if the passed arguments present is the given string else it should return false.
Advertisement
Answer
A generic solution is to have the “accumulator” value passed in differently. The first call you do to isPresent
should already call the closure, and isPresent()
should also work.
JavaScript
1
13
13
1
function makePresenceChecker(string, found) {
2
return function(char) {
3
if (char == undefined)
4
return found;
5
else
6
return makePresenceChecker(string, found && string.includes(char));
7
};
8
}
9
10
const isPresent = makePresenceChecker("ajkjxa", true);
11
12
console.log(isPresent("a")("j")("x")()); // true
13
console.log(isPresent("a")("j")("x")('b')()); // false
You can also write that with an IIFE:
JavaScript
1
12
12
1
const string = "ajkjxa";
2
const isPresent = (function makePresenceChecker(found) {
3
return function(char) {
4
if (char == undefined)
5
return found;
6
else
7
return makePresenceChecker(found && string.includes(char));
8
};
9
})(true);
10
11
console.log(isPresent("a")("j")("x")()); // true
12
console.log(isPresent("a")("j")("x")('b')()); // false