[Functional Programming] Draw Items from One JavaScript Array to Another using a Pair ADT

We want to be able to pick nine random cards from an array of twelve cards, but can run into problems of keeping both the cards already draw and the cards left to draw from. Tracking two bits of state like this can create some hard to maintain argument gymnastics when creating our functions. Luckily we have a datatype Pair at our disposal that allows us to combine two values in to one value.

We will use this Pair type to model both a draw pile and a remaining pile, and take advantage of a couple special properties of Pair that will allow us to combine two Pair instances in a meaningful way by chaining. Just like we have done time and time again with the State ADT.

 

We have generated array of cards:

复制代码
[ 
  { id: 'orange-square', color: 'orange', shape: 'square' },
  { id: 'orange-triangle', color: 'orange', shape: 'triangle' },
  { id: 'orange-circle', color: 'orange', shape: 'circle' },
  { id: 'green-square', color: 'green', shape: 'square' },
  { id: 'green-triangle', color: 'green', shape: 'triangle' },
  { id: 'green-circle', color: 'green', shape: 'circle' },
  { id: 'blue-square', color: 'blue', shape: 'square' },
  { id: 'blue-triangle', color: 'blue', shape: 'triangle' },
  { id: 'blue-circle', color: 'blue', shape: 'circle' },
  { id: 'yellow-square', color: 'yellow', shape: 'square' },
  { id: 'yellow-triangle', color: 'yellow', shape: 'triangle' },
  { id: 'yellow-circle', color: 'yellow', shape: 'circle' } ]
复制代码

 

By the following code:

复制代码
const {prop,assoc, pick, State, identity, omit, curry, filter, fanout, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
const  {get, modify, of} = State; 

// #region generateCards
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) => ({
    id: `${color}-${shape}`,
    color,
    shape
}));
const buildCards = liftA2(buildCard)
const generateCards = converge(
    liftA2(buildCards),
    getColors,
    getShapes
)
// #endregion
复制代码

 

Now what we want to do is split cards array into a Pair,

on the left side pair is the selected card array,

on the rigth side pair is the unselected cards array.

复制代码
// Splite Cards into two pars
//[Selected Cards] - [UnSelected Cards]

const getAt = index => array => array[index];
const unsetAt = index => array => ([...array.slice(0, index), ...array.slice(index + 1)]);
// Deck :: Pair [Card] [Card]
// drawCardAt :: Integer -> [Card] -> Deck
const drawCardAt = index => fanout(
    getAt(index),
    unsetAt(index)
)

console.log(
    generateCards()
        .map(drawCardAt(0))
        .evalWith(state).fst() 
) // { id: 'orange-square', color: 'orange', shape: 'square' }

console.log(
    generateCards()
        .map(drawCardAt(0))
        .evalWith(state).snd()
    
)
/** 
[ { id: 'orange-triangle', color: 'orange', shape: 'triangle' },
  { id: 'orange-circle', color: 'orange', shape: 'circle' },
  { id: 'green-square', color: 'green', shape: 'square' },
  { id: 'green-triangle', color: 'green', shape: 'triangle' },
  { id: 'green-circle', color: 'green', shape: 'circle' },
  { id: 'blue-square', color: 'blue', shape: 'square' },
  { id: 'blue-triangle', color: 'blue', shape: 'triangle' },
  { id: 'blue-circle', color: 'blue', shape: 'circle' },
  { id: 'yellow-square', color: 'yellow', shape: 'square' },
  { id: 'yellow-triangle', color: 'yellow', shape: 'triangle' },
  { id: 'yellow-circle', color: 'yellow', shape: 'circle' } ]
*/
复制代码

Here we use 'fanout' to generate a Pair.

 

Notice that the left side pair is an object, not an array, we need to use 'bimap' to lift left side pair into Array. To do that,. we use 'bimap'

复制代码
const drawCardAt = index => compose(
    bimap(Array.of, identity),
    fanout(
        getAt(index),
        unsetAt(index)
    )
)

console.log(
    generateCards()
        .map(drawCardAt(0))
        .evalWith(state).fst() 
) // [{ id: 'orange-square', color: 'orange', shape: 'square' }]
复制代码

 

---

复制代码
const {prop,assoc, pick, bimap, State, identity, omit, curry, filter, fanout, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
const  {get, modify, of} = State; 

// #region generateCards
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) => ({
    id: `${color}-${shape}`,
    color,
    shape
}));
const buildCards = liftA2(buildCard)
const generateCards = converge(
    liftA2(buildCards),
    getColors,
    getShapes
)
// #endregion

// Splite Cards into two pars
//[Selected Cards] - [UnSelected Cards]

const getAt = index => array => array[index];
const unsetAt = index => array => ([...array.slice(0, index), ...array.slice(index + 1)]);
// Deck :: Pair [Card] [Card]
// drawCardAt :: Integer -> [Card] -> Deck
const drawCardAt = index => compose(
    bimap(Array.of, identity),
    fanout(
        getAt(index),
        unsetAt(index)
    )
)

console.log(
    generateCards()
        .map(drawCardAt(0))
        .map(chain(drawCardAt(2)))
        .map(chain(drawCardAt(3)))
        .map(chain(drawCardAt(4)))
        .evalWith(state).fst() 
) /**
[ { id: 'orange-square', color: 'orange', shape: 'square' },
  { id: 'green-square', color: 'green', shape: 'square' },
  { id: 'green-circle', color: 'green', shape: 'circle' },
  { id: 'blue-triangle', color: 'blue', shape: 'triangle' } ]
*/

console.log(
    generateCards()
        .map(drawCardAt(0))
        .map(chain(drawCardAt(2)))
        .map(chain(drawCardAt(3)))
        .map(chain(drawCardAt(4)))
        .evalWith(state).snd()
    
)
/** 
[ { id: 'orange-triangle', color: 'orange', shape: 'triangle' },
  { id: 'orange-circle', color: 'orange', shape: 'circle' },
  { id: 'green-triangle', color: 'green', shape: 'triangle' },
  { id: 'blue-square', color: 'blue', shape: 'square' },
  { id: 'blue-circle', color: 'blue', shape: 'circle' },
  { id: 'yellow-square', color: 'yellow', shape: 'square' },
  { id: 'yellow-triangle', color: 'yellow', shape: 'triangle' },
  { id: 'yellow-circle', color: 'yellow', shape: 'circle' } ]
*/
复制代码

 

posted @   Zhentiw  阅读(188)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-01-17 [Transducer] Lazyness in Transduer
2018-01-17 [Transducer] Create a Sequence Helper to Transduce Without Changing Collection Types
2018-01-17 [Transducer] Make an Into Helper to Remove Boilerplate and Simplify our Transduce API
2018-01-17 [ML] Daily Portfolio Statistics
2017-01-17 [Angular Directive] Structure directive and <template>
2017-01-17 [React] Break up components into smaller pieces using Functional Components
2017-01-17 [TypeScript] Simplify asynchronous callback functions using async/await
点击右上角即可分享
微信分享提示