-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction.js
More file actions
121 lines (112 loc) · 3.2 KB
/
function.js
File metadata and controls
121 lines (112 loc) · 3.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
* 1.(函数柯里化) 是一种将使用多个参数的一个函数转换成一系列使用一个参数的函数的技术。
* @param {function} fn 需要柯里化的函数
* @param {arg} args 函数参数
* @return {function} 柯里化之后的函数
*/
export function curry(fn, args) {
var length = fn.length;
args = args || [];
return function () {
var _args = args.slice(0),
arg, i;
for (i = 0; i < arguments.length; i++) {
arg = arguments[i];
_args.push(arg);
}
if (_args.length < length) {
return curry.call(this, fn, _args);
} else {
return fn.apply(this, _args);
}
}
}
export function curry(fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
let innerArgs = Array.prototype.slice.call(arguments);
let finalArgs = args.concat(innerArgs);
return fn.apply(null, finalArgs);
}
}
/**
* @example
* var fn = curry(function (a, b, c) {
* console.log([a, b, c]);
* });
* fn("a", "b", "c") // ["a", "b", "c"]
* fn("a", "b")("c") // ["a", "b", "c"]
* fn("a")("b")("c") // ["a", "b", "c"]
* fn("a")("b", "c") // ["a", "b", "c"]
*/
/**
* 2.(组合函数)
* @param {function} 需要组合的函数
* @return {function} 组合完成之后的函数
*/
export function compose() {
// 获取要compose的 函数名数组
var args = arguments;
// 从右往左执行 获取参数的起始值
var start = args.length - 1;
// 匿名函数this指向
return function () {
var i = start;
// apply 参数为数组
// result 为 右侧第一个函数执行结果
var result = args[start].apply(this, arguments);
while (i--) {
result = args[i].call(this, result)
}
return result;
};
};
/**
* @example
* function hello(x) {
* return `hello ${x}`
* };
*
* function toBig(x) {
* return x.toUpperCase();
* }
* let composeFun = compose(hello, toBig)
*/
/**
* 3.(函数记忆) 把上次计算的结果缓存起来,当下次调用时,如果遇到相同参数,就直接返回缓存中的数据
* @param {function} func
* @return {function} 拥有缓存的函数
*/
export function memory(func) {
// 声明一个闭包缓存函数执行结果
let cache = {};
return function () {
// arguments 为对象 长度一样 则需要重写key 规则
let key = arguments.length + Array.prototype.join.call(arguments, ',')
if (cache[key]) {
return cache[key];
} else {
return cache[key] = func.apply(this, arguments);
}
}
}
// 参数为对象版
export const memoize = function (func, hasher) {
const memoize = function (key) {
const cache = memoize.cache;
const address = '' + (hasher ? hasher.apply(this, arguments) : key);
if (!cache[address]) {
cache[address] = func.apply(this, arguments);
}
return cache[address];
};
memoize.cache = {};
return memoize;
};
/**
* 4.(函数强制参数)
* @example (a=required(),b=required)=>{a+b};
*/
export const required = () => {
throw new Error(`Missing parameter`)
}