我在解决JS和纯函数中的问题时感到很头疼。下面的一个是不纯函数的例子,但有助于理解它的作用。
function fn(some) {
var ret = 'g',
mid = 'o';
if (some) return ret + some;
ret += mid;
return function d(thing) {
if (thing) return ret += thing;
ret += mid;
return d;
}
}
// Some output examples
fn('l') => 'gl'
fn()('l') => 'gol'
fn()()()()()()()()('l') => 'gooooooool'
如果我需要使其纯净以避免任何副作用怎么办?在以下示例中,显示了不纯函数的问题。
var state = fn()();
state('l') => 'gool'
state()()()('z') => 'goooooz' // ...and not 'gooloooz'
谢谢!
答案 0 :(得分:0)
现在我找到了你! :d
fn
是纯粹的,但它返回的函数不是。
您可以通过以下方法获得预期的行为:
function accumulate (accumulator) {
return function (value) {
return value ? accumulator + value : accumulate(accumulator + 'o');
};
}
function fn(some) {
return accumulate('g')(some);
}