Skip to content
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

Open
Sunny-117 opened this issue Nov 3, 2022 · 4 comments
Open

before #117

Sunny-117 opened this issue Nov 3, 2022 · 4 comments

Comments

@Sunny-117
Copy link
Owner

before(num,fn)接受两个参数,第一个参数是数字,第二个参数是函数,调用before函数num次数以内,返回与fn执行相同的结果,超过num次数返回最后一次fn的执行结果。
@CXGBro
Copy link

CXGBro commented Dec 25, 2022

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

@bearki99
Copy link

function before(num, fn) {
  let cnt = 0;
  let ans;
  return function (...args) {
    if (num > cnt) {
      ans = fn(...args);
    }
    cnt++;
    return ans;
  };
}

闭包应用

@veneno-o
Copy link
Contributor

veneno-o commented Mar 10, 2023

// 本来想试试迭代器,不过用现闭包才是正解
function before(num, callback){
    let res;
    return function (...args){
        if(num-- > 0){
            res = callback(...args)
            return res;
        }
        return res;
    }
}

@kangkang123269
Copy link

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants