-
Notifications
You must be signed in to change notification settings - Fork 25
/
AltManager.js
85 lines (72 loc) · 1.74 KB
/
AltManager.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
80
81
82
83
84
85
/**
* AltManager(Alt: AltClass): undefined
*
* > AltManager Util
*
* AltManager util allows for a developer to create multiple alt instances in
* their app. This is useful for building apps that encapsulates an alt instance
* inside of a outer parent. Popular examples include HipMunk flight search or
* Google Spreadsheets's multiple sheet tabs. This also allows for caching of
* client side instance if you need to store a new copy of an alt for each
* action.
*
* Usage:
*
* ```js
* var Alt = require('alt'); // Alt class, not alt instance
* var altManager = new AltManager(Alt);
*
* var altInstance = altManager.create('uniqueKeyName');
* altInstance.createAction(SomeAction);
* var someOtherOtherAlt = altManager.create('anotherKeyName');
* altManager.delete('uniqueKeyName');
*
* ```
*/
export default class AltManager {
constructor(Alt) {
this.Alt = Alt
this.alts = {}
}
create(altKey) {
if (this.get(altKey)) {
throw new ReferenceError(`Alt key ${altKey} already exists`)
}
if (typeof altKey !== 'string') {
throw new TypeError('altKey must be a string')
}
this.alts[altKey] = new this.Alt()
return this.alts[altKey]
}
get(altKey) {
return this.alts[altKey]
}
// returns all alt instances
all() {
return this.alts
}
findWhere(regex) {
const results = {}
for (const i in this.alts) {
if (regex.exec(i) === null) {
continue
}
results[i] = this.alts[i]
}
return results
}
delete(altKey) {
if (!this.get(altKey)) {
return false
}
delete this.alts[altKey]
return true
}
getOrCreate(altKey) {
const alt = this.get(altKey)
if (alt) {
return alt
}
return this.create(altKey)
}
}