我正试着用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
如果传递的参数是给定的字符串,我希望isPresent函数应该返回true,否则它应该返回false。
发布于 2021-10-08 23:55:48
一种通用的解决方案是以不同的方式传入“累加器”值。您对isPresent的第一个调用应该已经调用了闭包,并且isPresent()也应该可以工作。
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
你也可以用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
发布于 2021-10-08 21:51:41
我回答这个问题主要是作为一个学习练习。经过很长时间的努力,我终于找到了一些我认为有效的方法。我使用了与初始示例不同的语法和命名,并在setup调用中传递了初始字符串。
这可能不是严格意义上的"currying“,因为我们只需要聚合布尔值。似乎没有必要编译函数调用列表,因为布尔结果就足够了。
正如注释中提到的,至少在纯JS中,在末尾返回函数是不必要的。在我写这篇文章的TypeScript中,我不能让类型以这种方式工作。(返回类型取决于参数类型,如果返回的是参数类型,则不能调用(boolean | function)。)
const startcurry = start => { // string
const results = []; // boolean[] (could be boolean instead)
function inner(maybeNext) { // string?
if (maybeNext) {
const next = maybeNext; // string (just for naming rule)
results.push(start.includes(next));
return inner;
}
return results.every(x => x);
}
return inner;
};
const s = "ajkjxa";
console.log(startcurry(s)("a")("j")("x")()); // true expected
console.log(startcurry(s)("a")("j")("x")('b')()); // false expected
console.log(startcurry(s)("a")("j")("x")('k')()); // true expected
console.log(startcurry(s)("a")("j")("x")('k')('c')()); // false expected
console.log(startcurry(s)()); // true expected
console.log(startcurry(s)("b")("a")()); // false expected
发布于 2021-10-09 17:29:12
您只需更改它,使其每次都检查'a‘,但递归地调用isPresent(b) (如果存在
let s = "ajkjxa";
function isPresent(a, valid=true) {
return function (b) {
let isValid = valid && s.includes(a);
if (b) return isPresent(b, isValid)
return isValid
};
}
console.log(isPresent("a")("j")("x")());//true expected
console.log(isPresent("a")("j")("x")('b')());//false expected
console.log(isPresent("a")("g")("l")());//false expected
console.log(isPresent("a")("s")("b")("b")());//false expected
console.log(isPresent("a")("s")("l")("a")());//false expected
编辑:移动到默认参数,更少的代码,它适用于注释中的用例。
https://stackoverflow.com/questions/69501816
复制相似问题