首页 > 编程语言 > 详细

[Javascript] Compose multiple functions for new behavior in JavaScript

时间:2017-11-30 18:36:55      阅读:219      评论:0      收藏:0      [点我收藏+]

In this lesson you will create a utility function that allows you to quickly compose behavior of multiple functions to create new behavior. By the end, you will have successfully created a tremendously popular helper function that is used in JavaScript libraries ranging from Redux to Ramda.

 

const startVal = 4;

const squared = x => x * x;
const doubled = x => x * 2;
const addTen = x => x + 10;
const halfNum = x => x / 2;

const result = halfNum(addTen(doubled(squared(startVal))));

The code above is not good enough. We can use ‘compose‘ function instead of nested functions call together.

 

Write ‘compose‘ function:

const compose = (...fns) => initialVal => fns.reduceRight((val, fn) => fn(val), initialVal)

 

Now we can optimizte the code:

const result = compose(
  halfNum,
  addTen,
  doubled,
  squared
)(startVal);

[Javascript] Compose multiple functions for new behavior in JavaScript

原文:http://www.cnblogs.com/Answer1215/p/7930242.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!