[Javascript] Write a function pipeline
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript] Write a function pipeline相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
[Javascript] Write a function pipeline
[GraphQL] Write a GraphQL Schema in JavaScript
[Javascript AST] 2. Write a simple ESLint rule
[Javascript AST] 1. Continue: Write a simple Babel plugin
[Javascript AST] 0. Introduction: Write a simple BabelJS plugin