Skip to content
Advertisement

Boolean Currying Javascript

I am trying to write a boolean currying function in javascript.

let s = "ajkjxa";

function isPresent(a) {

return function (b) {

  if (b) {
    return isPresent(s.includes(b) && s.includes(a));
  } else {
    return s.includes(a);
  }
 };
}

console.log(isPresent("a")("j")("x")());//true expected
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.

function makePresenceChecker(string, found) {
  return function(char) {
    if (char == undefined)
      return found;
    else
      return makePresenceChecker(string, found && string.includes(char));
  };
}

const isPresent = makePresenceChecker("ajkjxa", true);

console.log(isPresent("a")("j")("x")()); // true
console.log(isPresent("a")("j")("x")('b')()); // false

You can also write that with an IIFE:

const string = "ajkjxa";
const isPresent = (function makePresenceChecker(found) {
  return function(char) {
    if (char == undefined)
      return found;
    else
      return makePresenceChecker(found && string.includes(char));
  };
})(true);

console.log(isPresent("a")("j")("x")()); // true
console.log(isPresent("a")("j")("x")('b')()); // false
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement