zoukankan      html  css  js  c++  java
  • [Functional Programming] Use a Javascript Array to Construct a Maybe

    Much of our code in real life is full of if statements that check the validity of a given input to see if a given computation should be performed. Using the ever popular Maybe construction allows us capture this disjunction in one place, keeping our functions free of similar if statements that can pollute the intention of the function. You do not even need a fancy library to get this benefit, as Javascript ships with everything you need with it's build in Array.

    const compose = (f, g) => x => f(g(x));
    
    const maybe = pred => x => pred(x) ? [x]: [];
    const mapMaybe = fn => m => m.map(fn);
    const optionMaybe = def => m => m.length > 0 ? m[0]: def;
    
    ///////////
    const add = a => b => a + b;
    const pow = a => a * a;
    const isValid = x => typeof x === 'number' && !Number.isNaN(x);
    
    ///////////
    const doMath = compose(
      pow,
      add(10)
    )
    const safeDoMath = compose(
      mapMaybe(doMath),
      maybe(isValid)
    );
    const option = (def) => compose(
      optionMaybe(def),
      safeDoMath
    )
    const app = option('Not a number')
    
    //////////
    const result = app();
    
    console.log(result)
    

      

  • 相关阅读:
    ESLint规则整理与实际应用
    node vue 项目git 管理
    Node.js安装及环境配置之Windows篇
    Windows服务 --- SqlDependency的使用
    插槽
    报表菜单的配置
    HTTP 错误 500.21
    项目部署错误 HTTP Error 500.19
    Steup factory 面板介绍
    Steup Factory 操作注册表
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12306147.html
Copyright © 2011-2022 走看看