zoukankan      html  css  js  c++  java
  • [Javascript] Multiply Two Arrays over a Function in JavaScript

    Just like the State ADT an Array is also an Applicative Functor. That means we can do the same tricks with liftA2 with Array that we have been doing with State.

    While the Applicative aspect of State allows use to combine multiple stateful transitions over a function, Array allows us to create a new Array that contains the results of calling every permutation of each element in two arrays over a function. We will use this ability to pull from two separate locations in our AppStateand generate an Array of Cards.

    liftA2 from crocks.js "Ever see yourself wanting to map a binary or trinary function, but map only allows unary functions? Both of these functions allow you to pass in your function as well as the number of Applicatives (containers that provide bothof and apfunctions) you need to get the mapping you are looking for."

    lift from Ramda.js "lifts" a function of arity > 1 so that it may "map over" a list, Function or other object that satisfies the FantasyLand Apply spec.

    // Crocks.js
    
    const buildCard = curry((color, shape) => console.log(color, shape) || ({
        id: `${color}-${shape}`,
        color,
        shape
    }));
    // buildCards :: [String] -> [String] -> [Card]
    const buildCards = liftA2(buildCard);
    
    
    // Ramda.js
    
    const build = lift(buildCard);

     --- 

    const {prop,assoc, pick, State, identity, omit, curry, filter, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
    const  {get, modify, of} = State; 
    const {lift} = require('ramda');
    
    const state = {
        colors: [ 'orange', 'green', 'blue', 'yellow' ],
        shapes: [ 'square', 'triangle', 'circle' ]
      };
    
    const getState = (key) => get(prop(key))
    const getColors = () => getState('colors').map(option([]));
    const getShapes = () => getState('shapes').map(option([]));
    
    const buildCard = curry((color, shape) => console.log(color, shape) || ({
        id: `${color}-${shape}`,
        color,
        shape
    }));
    // buildCards :: [String] -> [String] -> [Card]
    const buildCards = liftA2(buildCard);
    const generateCards = converge(
        liftA2(buildCards),
        getColors,
        getShapes
    )
    console.log(
        generateCards()
            .evalWith(state)
    )
    
    const build = lift(buildCard);
    console.log('build', build([1,2,3], ['c', 'd']))
  • 相关阅读:
    DataTablez转List对象效率慢的问题.
    Oracle 删除重复数据
    1.layui 添加旋转等待, 2.div里面加载HTML页面
    layui-table JSON.stringify()序列化出来的不同行数据类型错误.导致后台转成表格的时候出错.(常用)
    0基础学MVC课程
    构造函数的执行顺序
    html控件自动点 “加号”添加 多个附件
    C#委托之个人理解 转自 loose_went
    一步一步学Linq to sql系列文章 转lovecherry
    使用AOP 使C#代码更清晰 转yanghua_kobe
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10277748.html
Copyright © 2011-2022 走看看