[Javascript] Use a Pure RNG with the State ADT to Select an Element from State
The resultant in a State ADT instance can be used as a means of communication between different stateful transactions. It can be used to read and transform a portion of our state into a form that another transaction is dependent on. This allows us to only keep what is needed state, without filling it with calculations that are only needed for one or few transactions.
We take can take advantage of this by pulling not only a random number using the seed from our state, but also pulling a list of card and filtering them, to randomly select one from our calculated state. Then we use the resultant to store the calculation before we save the result to state.
Code for Random generator is here, which is not so important to this blog.
const {prop,assoc, 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 state = { cards: [ {id: 'green-square', color: 'green', selected: true, shape: 'square'}, {id: 'orange-square', color: 'orange', shape: 'square'}, {id: 'blue-triangle', color: 'blue', shape: 'triangle'} ], hint: null, seed: Date.now() } // #region helper const liftState = fn => compose( of, fn ) // nextSeed :: Integer -> Integer const nextSeed = seed => (seed * 1103515245 + 12345) & 0x7fffffff // value :: Integer -> Number const value = seed => (seed >>> 16) / 0x7fff // normalize :: (Integer, Integer) -> Number -> Integer const normalize = (min, max) => x => Math.floor(x * (max - min)) + min // getNextSeed :: () -> State AppState Integer const getNextSeed = () => get(({ seed }) => nextSeed(seed)) // updateSeed :: Integer -> State AppState () const updateSeed = seed => modify(assoc('seed', seed)) // nextValue :: Integer -> State AppState Number const nextValue = converge( liftA2(constant), liftState(value), updateSeed ) // random :: () -> State AppState Number const random = composeK(nextValue, getNextSeed) // #endregion // between :: (Integer, Integer) -> State AppState Integer const between = (min, max) => random() .map(normalize(min, max));
The only important piece is 'bewteen' function, which can generate the Number between a min & max range.
The idea for what we are going to achieve is that:
- Select all the unselected cards
- Randomly choose one unselected card by using random function
- Set the hint according to the selected card.
First, select all the unselected cards:
const selectState = (key, fn) => get( compose( map(fn), prop(key) ) ) const unselected = ({selected}) => !selected; const getUnselectedCards = () => selectState('cards', filter(unselected)).map(option([]))
Second: Rnadomly choose one unselected card by using random function:
// randomIndex :: [a] -> State AppState a const randomIndex = arr => between(0, arr.length) const getAt = index => arr => arr[index]; const pickCard = converge( liftA2(getAt), randomIndex, liftState(identity) )
Last, Set the hint according to the selected card:
const over = (key, fn) => modify( mapProps({[key]: fn}) ) const toHint = pick(['color', 'shape']) // setHint :: Card -> State AppState() const setHint = card => over('hint', constant(toHint(card))) const nextHint = composeK( setHint, pickCard, getUnselectedCards )
-----------------
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 state = { cards: [ {id: 'green-square', color: 'green', selected: true, shape: 'square'}, {id: 'orange-square', color: 'orange', shape: 'square'}, {id: 'blue-triangle', color: 'blue', shape: 'triangle'} ], hint: null, seed: Date.now() } // #region helper const liftState = fn => compose( of, fn ) // nextSeed :: Integer -> Integer const nextSeed = seed => (seed * 1103515245 + 12345) & 0x7fffffff // value :: Integer -> Number const value = seed => (seed >>> 16) / 0x7fff // normalize :: (Integer, Integer) -> Number -> Integer const normalize = (min, max) => x => Math.floor(x * (max - min)) + min // getNextSeed :: () -> State AppState Integer const getNextSeed = () => get(({ seed }) => nextSeed(seed)) // updateSeed :: Integer -> State AppState () const updateSeed = seed => modify(assoc('seed', seed)) // nextValue :: Integer -> State AppState Number const nextValue = converge( liftA2(constant), liftState(value), updateSeed ) // random :: () -> State AppState Number const random = composeK(nextValue, getNextSeed) // #endregion // between :: (Integer, Integer) -> State AppState Integer const between = (min, max) => random() .map(normalize(min, max)); // Get all unselected card // Randomly choose an unselected Card // Set hint const selectState = (key, fn) => get( compose( map(fn), prop(key) ) ) const unselected = ({selected}) => !selected; const getUnselectedCards = () => selectState('cards', filter(unselected)).map(option([])) // randomIndex :: [a] -> State AppState a const randomIndex = arr => between(0, arr.length) const getAt = index => arr => arr[index]; const pickCard = converge( liftA2(getAt), randomIndex, liftState(identity) ) const over = (key, fn) => modify( mapProps({[key]: fn}) ) const toHint = pick(['color', 'shape']) // setHint :: Card -> State AppState() const setHint = card => over('hint', constant(toHint(card))) const nextHint = composeK( setHint, pickCard, getUnselectedCards ) console.log( nextHint() .execWith(state) )
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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-15 [Mobx] Using mobx to isolate a React component state
2018-01-15 [Javascript] Simplify Creating Immutable Data Trees With Immer
2018-01-15 [React Native] Dismiss the Keyboard in React Native
2018-01-15 [CSSinJS] Convert Sass (SCSS) Styled Button to CSSinJS with JavaScript Templates and Variables
2016-01-15 [Redux] React Todo List Example (Filtering Todos)
2016-01-15 [Javascript] How to use JavaScript's String.replace
2016-01-15 [Javascript] Regex: '$`', '$&', '$''