Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

es6 还原 es5

const compose = f => g => x => f(g(x));

const f = compose (x => x * 4) (x => x + 3);
f(2) // 20

求一个化简后的compose!!!!!!.......还有为什么f(2)等于8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
"use strict";

var compose = function compose(f) {
  return function (g) {
    return function (x) {
      return f(g(x));
    };
  };
};
var f = compose(function (x) {
  return x * 4;
})(function (x) {
  return x + 3;
});
f(2);

地址

可能给compose的参数换个名字更阅读一些?

var compose = function(a) {
    return function(b) {
        return function(c) {
            return a(b(c));
        };
    };
};
var f = compose(function(x) {
    return x * 4;
})(function(x) {
    return x + 3;
});
console.log(f(2));
调用的话一共有三次
var f = compose(function(x) {
    return x * 4;
})(function(x) {
    return x + 3;
});
两次
f(2)
一次

三次调用再拆为

var f1=compose(function(x) {
    return x * 4;
})
var f2 = f1(function(x) {
    return x + 3;
})
f2(2);
  1. compose(function(x) {return x * 4;})即参数a为函数function(x) {return x * 4;}内部a(b(c))相当于对a调用内部参数xb(c),得到function(b){return function(c){return b(c)*4}}

  2. 此时 f1 = function(b){return function(c){return b(c)*4}}同样对f1的调用f1(function(x) {return x + 3;})相当与参数bfunction(x){return x+3},内部b(c)相当于将c作为参数传入b中,得到function(c){return (c+3)*4}

  3. 此时f2=function(c){return (c+3)*4},f2(2)=20

有点绕,可以拿笔和纸写一下。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...