deno.land / x / rambda@v9.1.1 / source / switcher.js

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { equals } from './equals.js'
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)}
rambda

Version Info

Tagged at
2 months ago