1、纯函数
a、确定的输入,一定会产生确定的输出 b、函数在执行过程中,不能产生副作用
var names = ["abc", "cba", "nab", "a"];
var newNames = names.slice(0, 3);
console.log(newNames);
console.log(names);
var newNames2 = names.splice(2);
console.log(newNames2);
console.log(names);
function baz(info) {
info.age = 23
}
var obj = {
name: 'chen',
age: 34
}
baz(obj);
console.log(obj);
console.log('============');
function test(info) {
return {
...info,
age: 123
}
}
test(obj)
console.log(obj);
2、柯里化
2.1、柯里化过程和代码结构
function foo(a, b, c, d) {
return a + b + c + d;
}
let f = foo(1, 2, 3, 4);
console.log(f);
function a(a) {
return function b(b) {
return function c(c) {
return function d(d) {
return a + b + c + d;
};
};
};
}
let a1 = a(1)(2)(3)(4);
console.log(a1);
var bar = (a) => (b) => (c) => (d) => {
return a + b + c + d;
};
console.log(bar(10)(20)(30)(40));
var bar2 = (a) => {
return (b) => {
return (c) => {
return (d) => {
a + b + c + d;
};
};
};
};
console.log(bar(10)(20)(30)(40));
2.2、柯里化作用
1、柯里化单一原则:
function add(x, y, z) {
x = x + 2;
y = y * 2;
z = z - 2;
return x + y + z;
}
console.log(add(1, 2, 3));
function sum(x) {
x = x + 2;
return function (y) {
y = y * 2;
return function (z) {
z = z - 2;
return x + y + z;
};
};
}
console.log(sum(1)(2)(3));
2、柯里化-逻辑的复用:
function sum(a, b) {
return a + b;
}
console.log(sum(5, 11));
console.log(sum(5, 12));
console.log(sum(5, 13));
console.log(sum(5, 14));
function makeAdder(count) {
return function (num) {
return count + num;
};
}
var result = makeAdder(5)(13);
console.log('result', result);
var add5 = makeAdder(5)
add5(11)
add5(12)
add5(13)
3、自动柯里化函数的实现:
function add(a, b, c) {
return a + b + c;
}
function fnCurrying(fn) {
function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
function curried2(...args2) {
return curried.apply(this, [...args, ...args2]);
}
return curried2;
}
}
return curried;
}
var curryAdd = fnCurrying(add);
console.log(curryAdd(10, 20, 30));
console.log(curryAdd(10)(20)(30));
console.log(curryAdd(10, 20)(30));
|