zoukankan      html  css  js  c++  java
  • [Functional Programming] Functional JS

    Learning notes. Video.

    Less than:

    If you use 'ramda', you maybe know 'lt, gt'..

    R.lt(2, 1); //=> false

    Is '2' less than '1' , the result is false. We can see that the data is actually come first which is 2.

    Normally in FP, we want data come last. What we can do is using 'flip' from 'crocks.js'.

    const {flip} = require('crocks')
    const {lt} = require('ramda')
    
    // isLessTen :: Number -> Boolean
    const isLessTen = flip(lt, 10)
    isLessThen(9) // true

    If/Else:

    const diff10 = v => {
        let result = null;
        if (v < 10) {
            result = v - 10
        } else {
            result = v + 10
        }
    }

    We can use 'ifElse' from 'crocks.js':

    const {not, ifElse} = require('crocks');
    const {add, lt} = require('ramda');
    
    const declarative = ifElse(
        not(flip(lt, 10)), // if the given number is greater than 10
        add(10), // then plus 10
        add(-10) // go negitive
    )

    or/and:

    /**
     * Or && And
     */
    // Just check one object has length prop is not enough
    // Because Array has length, function has length
    // Array is also object
    const _hasLengthProp = x =>
        (isObject(x) && x.length !== undefined) || isArray(x);
    
    // hasLengthProp :: a -> Boolean
    const hasLengthProp = or(isArray, and(isObject, hasProp('length')));
    log(hasLengthProp([])) // true

    [100] === [100]?

    The Answer is : false

    JS consider each [] is a new Object. 

    In this case, we can use 'propEq' from 'crocks.js' to save us some safe checking:

    const _aIs100A = x => isObject(x) && x.a === [100];
    log(
        _aIs100A({a: [100]})
    ) // false, because it consider [100] is a new object
    const aIs100A = and(isObject, propEq('a', [100]))
    log(
        aIs100A({a: [100]}) // true
    )

    ES5 way to check Array is typeof Array, and Date is typeof Date:

    const _isArray = x => Object.prototype.toString.call(x) === '[object Array]';
    const _isDate = x => Object.prototype.toString.call(x) === '[object Date]';
  • 相关阅读:
    [JZOJ3386] 守卫者的挑战
    [JZOJ3385] 黑魔法师之门
    [JZOJ3383] 太鼓达人
    [JZOJ3382] 七夕祭
    NOIP模拟测试on 2019.9.27
    数据结构测试2 on 2019.9.25
    数据结构测试1 on 2019.9.24
    P2047 [NOI2007]社交网络
    P2286 [HNOI2004]宠物收养场
    P1342 请柬 建反图+dijkstra
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10779156.html
Copyright © 2011-2022 走看看