码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Compose multiple functions for new behavior in JavaScript

时间:2017-11-30 19:19:20      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:square   multiple   http   div   ...   call   aries   new   javascrip   

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

标签:square   multiple   http   div   ...   call   aries   new   javascrip   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!