zoukankan      html  css  js  c++  java
  • [Javascript] Understand Function Composition By Building Compose and ComposeAll Utility Functions

    Function composition allows us to build up powerful functions from smaller, more focused functions. In this lesson we'll demystify how function composition works by building our own compose and composeAll functions.

    // __test__ 
    
    import {add, inc, dbl, addInc, addIncDbl} from '../function/custom-compose';
    
    describe('basic fns', () => {
        "use strict";
        test('add', () => {
            const res = add(1,2);
            const expected = 3;
            expect(res).toBe(expected);
        });
    
        test('inc', () => {
            const res = inc(2);
            const expected = 3;
            expect(res).toBe(expected);
        });
    
        test('dbl', () => {
            const res = dbl(2);
            const expected = 4;
            expect(res).toBe(expected);
        });
    });
    
    describe('compose', () => {
        "use strict";
        test('add then inc', () => {
            const res = addInc(4, 2);
            const expected = 7;
            expect(res).toBe(expected);
        });
    });
    
    describe('composeAll', () => {
        "use strict";
       test('add, inc then dbl', () => {
           const res = addIncDbl(2, 3);
           const expected = 12;
           expect(res).toBe(expected);
       }) ;
    });
    /*
    * Utils
    * */
    const compose = (f, g) => (...args) => f(g(...args));
    
    const composeAll = (...fns) => fns.reduce(compose);
    /*
    * Libs
    * */
    export const add = (a, b) => a + b;
    
    export const inc = (a) => a + 1;
    
    export const dbl = (a) => a * 2;
    
    export const addInc = compose(inc, add);
    
    export const addIncDbl = composeAll(dbl, inc, add);
  • 相关阅读:
    (4)使用 JDK8 日期時間 API
    (3)使用 Joda-Time
    (2)時間的 ABC
    (1)Date 與 Calendar 怎麼了?
    Android 开发绕不过的坑:你的 Bitmap 究竟占多大内存?
    AsyncTask 源码阅读笔记
    LinkedHashMap 阅读笔记
    HashMap 阅读笔记
    DiskLruCache 阅读笔记
    Android面试复习
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6667130.html
Copyright © 2011-2022 走看看