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

[Javascript] Write a function pipeline

时间:2017-02-02 19:57:27      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:asc   utils   code   imp   work   blog   with   from   style   

const _pipe = (f, g) => (...args) => g(f(...args))

export const pipe = (...fns) => fns.reduce(_pipe)

 

import {partial, pipe} from ./utils

const add = (a, b) => a + b
const addThree = (a, b, c) => a + b + c
const inc = (num) => num + 1
const dbl = (num) => num * 2

test(pipe passes the results of inc to dbl, () => {
  const pipeline = pipe(inc, dbl) // => dbl(inc(2)) OR g(f(...args))
  const result = pipeline(2)
  expect(result).toBe(6)
})

test(pipe passes the results of dbl to inc, () => {
  const pipeline = pipe(dbl, inc) // => inc(dbl(2))
  const result = pipeline(2)
  expect(result).toBe(5)
})

test(pipe works with more than 2 functions, () => {
  const pipeline = pipe(add, inc, dbl, inc) // => inc(dbl(inc(add(1,2))))
  const result = pipeline(1,2)
  expect(result).toBe(9)
})

 

[Javascript] Write a function pipeline

标签:asc   utils   code   imp   work   blog   with   from   style   

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

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