Skip to main content
Module

x/rambda/switcher.js

Faster and smaller alternative to Ramda
Go to Latest
File
import { equals } from './equals'
const NO_MATCH_FOUND = Symbol ? Symbol('NO_MATCH_FOUND') : undefined
const getMatchingKeyValuePair = ( cases, testValue, defaultValue) => { let iterationValue
for (let index = 0; index < cases.length; index++){ iterationValue = cases[ index ].test(testValue)
if (iterationValue !== NO_MATCH_FOUND){ return iterationValue } }
return defaultValue}
const isEqual = (testValue, matchValue) => { const willReturn = typeof testValue === 'function' ? testValue(matchValue) : equals(testValue, matchValue)
return willReturn}
const is = (testValue, matchResult = true) => ({ key : testValue, test : matchValue => isEqual(testValue, matchValue) ? matchResult : NO_MATCH_FOUND,})
class Switchem{ constructor( defaultValue, cases, willMatch ){ if (cases === undefined && willMatch === undefined){ this.cases = [] this.defaultValue = undefined this.willMatch = defaultValue } else { this.cases = cases this.defaultValue = defaultValue this.willMatch = willMatch }
return this }
default(defaultValue){ const holder = new Switchem( defaultValue, this.cases, this.willMatch )
return holder.match(this.willMatch) }
is(testValue, matchResult){ return new Switchem( this.defaultValue, [ ...this.cases, is(testValue, matchResult) ], this.willMatch ) }
match(matchValue){ return getMatchingKeyValuePair( this.cases, matchValue, this.defaultValue ) }}
export function switcher(input){ return new Switchem(input)}