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

实现中间件 #88

Open
nmsn opened this issue Jul 27, 2023 · 1 comment
Open

实现中间件 #88

nmsn opened this issue Jul 27, 2023 · 1 comment

Comments

@nmsn
Copy link
Contributor

nmsn commented Jul 27, 2023

/*
 * 实现中间件机制
 */
function rawMethod(a) {
  return a + 1;
}

function middleware1(next) {
  return function (a) {
    return next(a) + 1;
  };
}

function middleware2(next) {
  return function (a) {
    return next(a) + 1;
  };
}

function middleware3(next) {
  return function (a) {
    return next(a) + 1;
  };
}

function applyMiddleWare(...args) {
  // 实现...
}

const newFun = applyMiddleWare(rawMethod, middleware2, middleware1);
console.log(newFun(0)); // middleware2 -> middleware1 -> rawMethod => 3

const newFun2 = applyMiddleWare(newFun, middleware3);
console.log(newFun2(0)); // middleware3 -> middleware2 -> middleware1 -> rawMethod => 4
@nmsn
Copy link
Contributor Author

nmsn commented Jul 27, 2023

reduce 实现

迭代实现

function applyMiddleWare(...args) {

  const [raw, ...func] = args;

  return function (a) {
    let result;

    func.reverse().forEach((f, index) => {
      result = f(result || raw);
    });

    return result(a);
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant