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

函数组合 #14

Open
BYChoo opened this issue Apr 22, 2021 · 0 comments
Open

函数组合 #14

BYChoo opened this issue Apr 22, 2021 · 0 comments

Comments

@BYChoo
Copy link
Owner

BYChoo commented Apr 22, 2021

函数饲养

这就是组合(compose)

var compose = function(f,g) {
  return function(x) {
    return f(g(x));
  };
};

fg 都是函数,x是在他们之间通过"管道"传输的值

组合看起来像是在饲养函数。你就是饲养员,选择两个有特点又遭你喜欢的函数,让它们结合,产下一个崭新的函数。组合的用法如下:

var toUpperCase = function(x) { return x.toUpperCase(); };
var exclaim = function(x) { return x + '!'; };

var shout = compose(exclaim, toUpperCase);

shout("send in the clowns");

应用compose函数

假定有这样一个需求:对一个给定的数字四舍五入求值,数字为字符型。

常规实现:

let n = '3.56'
let data = parseFloat(n)
let result = Math.round(data) // => 4 最终结果

用compose函数改写:

let n = '3.56'
let number = compose(Math.round,parseFloat)
let result = number(n); // =>4 最终结果
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