-
-
Notifications
You must be signed in to change notification settings - Fork 241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
before #117
Comments
function before(num, fn) {
let count = 0
let beforeNumRes
return function (...args) {
if (num > count) {
beforeNumRes = fn(...args)
}
count += 1
return beforeNumRes
}
}
let func = before(3, (a, b) => a + b)
console.log(func(1, 2)); // 3
console.log(func(2, 3)); // 5
console.log(func(1, 6)); // 7
console.log(func(1, 8)); // 7 |
function before(num, fn) {
let cnt = 0;
let ans;
return function (...args) {
if (num > cnt) {
ans = fn(...args);
}
cnt++;
return ans;
};
} 闭包应用 |
// 本来想试试迭代器,不过用现闭包才是正解
function before(num, callback){
let res;
return function (...args){
if(num-- > 0){
res = callback(...args)
return res;
}
return res;
}
} |
function before(num, fn) {
let count = 0;
let lastResult;
return function(...args) {
if (count < num) {
lastResult = fn.apply(this, args);
count++;
}
return lastResult;
};
}
let testFn = function(x) { return x * x; };
let beforeTestFn = before(3, testFn);
console.log(beforeTestFn(2)); // 输出 4
console.log(beforeTestFn(3)); // 输出 9
console.log(beforeTestFn(4)); // 输出 16
console.log(beforeTestFn(5)); // 输出 16,因为已经超过了3次调用,所以返回最后一次执行结果。 |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: