-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbranch.ts
More file actions
61 lines (53 loc) · 1.56 KB
/
branch.ts
File metadata and controls
61 lines (53 loc) · 1.56 KB
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
import { DualCompareFunction } from '../compare'
/**
* A type used to identify a branch. This value should be used to look up a
* user-presentable name in another map stored outside of `logootish-js`. This
* is implementation-defined and allows for the broadest possible definition of
* a branch.
*/
type BranchKey = symbol | string | number
class BranchOrder<T extends BranchKey = BranchKey> {
constructor(public readonly order: T[] = []) {}
get length(): number {
return this.order.length
}
/**
* Finds the index of `br` and adds it to the order if necessary.
* @param br The branch to find the index of
* @return The index of `br`
*/
i(br: T): number {
if (!this.order.includes(br)) {
this.order.push(br)
return this.order.length - 1
}
return this.order.indexOf(br)
}
b(index: number): T {
return this.order[index]
}
insertOrdered(br: T, cf: DualCompareFunction<T>): BranchOrder<T> {
const len = this.order.length
for (let i = 0; i < len; i++) {
if (cf(br, this.order[i]) < 0) {
this.order.splice(i, 0, br)
return this
}
}
this.order.push(br)
return this
}
static fromJSON(
// eslint-disable-next-line
json: any[],
// eslint-disable-next-line
mapper: (k: any) => BranchKey = (k: any): BranchKey => k
): BranchOrder {
return new BranchOrder(json.map(mapper))
}
// eslint-disable-next-line
toJSON(mapper: (k: BranchKey) => any = (k: BranchKey): any => k): any[] {
return this.order.map(mapper)
}
}
export { BranchKey, BranchOrder }