超级面板
文章目录
最新文章
最近更新
文章分类
标签列表
文章归档

常用的高阶函数之控制执行次数

控制次数其实主要从两方面着手,一方面是简单的限制函数的执行次数,而另一方面可以缓存函数的执行结果。

限制函数的执行次数

对于有些场景下可能需要控制执行次数,比如设置错误重试次数5次,比如表单提交函数只允许执行一次防止重复提交。

function limit(fn, limit, context) {
let current = 0;
return function(...args) {
if (current >= limit) {
return -1; // 或者返回其它有意义的内容
}
current += 1;

let ctx = context || this;
return fn.apply(ctx, args);
}
}

function foo(id) {
console.log(id);
}

foo(1); // log 1
foo(2); // log 2
foo(3); // log 3

foo = limit(foo, 1); // 限制只执行一次

foo(4); // log 4
foo(5); // do nothing
foo(6); // do nothing

缓存函数的执行结果

对于一些执行成本非常高的操作或者会被反复调用的操作,可以通过缓存,限制其执行次数。

function memorize(func, context) {
let cache = {};
return function(...args) {
let address = args.length + args.join(",");
if (cache[address] === undefined) {
cache[address] = func.apply(context || this, args);
}
return cache[address];
};
};

// 使用斐波那契数列测试
let count = 0;
let fibonacci = n => {
count ++;
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}

for (let i = 0; i < 10; i ++) {
2fibonacci(i);
}
console.log(count); // 276

fibonacci = memorize(fibonacci);
count = 0;
for (let i = 0; i < 10; i ++) {
2fibonacci(i)
}
console.log(count); // 10
0 comments
Anonymous
Markdown is supported

Be the first person to leave a comment!