-
Notifications
You must be signed in to change notification settings - Fork 0
/
overloads.js
36 lines (34 loc) · 1.11 KB
/
overloads.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
class Overload {
static fallback() { throw new Error("Arguments matched no provided definition while no fallback was defined") }
handleEvent(...args) {
const boxed = args.map(raw =>
raw instanceof Object || (raw === null || raw === undefined) ?
raw : new raw.constructor(raw))
const found = this.definitions.slice().reverse().find(([fn, ...types]) =>
types.every((T, i) => boxed[i] instanceof T))
return found ? found[0](...args) : this.fallback(...args)
}
if(...definition) {
definition.unshift(definition.pop())
this.definitions.push(definition)
return this
}
any(fn) {
this.fallback = fn
return this
}
lock() {
return this.bind(null)
}
}
export function overload() {
const load = new Overload()
const loader = (...args) => loader.handleEvent(...args)
loader.definitions = []
loader.fallback = Overload.fallback
loader.if = load.if
loader.else = load.any
loader.lock = load.lock
loader.handleEvent = load.handleEvent
return loader
}