-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Description
For reference. This should probably replace the ES6 version:
interface PredicateFunction {
(): boolean
}
interface WithFunction {
(condition: PredicateFunction | any, result: any): PatternMatch
}
interface ElseFunction {
(result: any): PatternMatch
}
interface DoFunction {
(value?: any): any
}
interface ToFuncFunction {
(): DoFunction
}
class PatternMatch {
with: WithFunction
else: ElseFunction
do: DoFunction
toFunc: ToFuncFunction
}
interface ResultFunction {
(value?: any): any
}
class PatternMatchCase {
condition: PredicateFunction | any
result: ResultFunction | any
}
export let patternMatch = matchOn => {
const self = new PatternMatch()
let cases: PatternMatchCase[] = []
let elseCase = null
self.with = (condition, result) => {
cases.push({
condition: condition,
result: result
})
return self
}
self.else = result => {
elseCase = result
return self
}
self.do = (value?) => {
value = (value || value === false) ? value : matchOn
for (let i in cases) {
let result = typeof cases[i].condition == 'function'
? cases[i].condition(value)
: cases[i].condition == value
if (result) {
return typeof cases[i].result == 'function'
? cases[i].result(value)
: cases[i].result
}
}
if (elseCase || elseCase === false) {
return typeof elseCase == 'function' ? elseCase(value) : elseCase
}
throw 'Incomplete pattern match'
}
self.toFunc = () => self.do
return self
}
mmc41
Metadata
Metadata
Assignees
Labels
No labels