-
Notifications
You must be signed in to change notification settings - Fork 2
/
chain.js
81 lines (61 loc) · 1.85 KB
/
chain.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
function DEFAULT_ADDRESS_FUNCTION (node) {
return node.getAddress()
}
function DEFAULT_DERIVE_FUNCTION (parent, index) {
return parent.derive(index)
}
function Chain (parent, k, addressFunction, deriveFunction) {
k = k || 0
this.__parent = parent
this.addresses = []
this.addressFunction = addressFunction || DEFAULT_ADDRESS_FUNCTION
this.deriveFunction = deriveFunction || DEFAULT_DERIVE_FUNCTION
this.k = k
this.map = {}
}
Chain.prototype.__initialize = function () {
var address = this.addressFunction(this.deriveFunction(this.__parent, this.k))
this.map[address] = this.k
this.addresses.push(address)
}
Chain.prototype.clone = function () {
var chain = new Chain(this.__parent, this.k, this.addressFunction)
chain.addresses = this.addresses.concat()
for (var s in this.map) chain.map[s] = this.map[s]
return chain
}
Chain.prototype.derive = function (address, parent) {
var k = this.map[address]
if (k === undefined) return
parent = parent || this.__parent
return this.deriveFunction(parent, k)
}
Chain.prototype.find = function (address) {
return this.map[address]
}
Chain.prototype.get = function () {
if (this.addresses.length === 0) this.__initialize()
return this.addresses[this.addresses.length - 1]
}
Chain.prototype.getAll = function () {
if (this.addresses.length === 0) this.__initialize()
return this.addresses
}
Chain.prototype.getParent = function () {
return this.__parent
}
Chain.prototype.next = function () {
if (this.addresses.length === 0) this.__initialize()
var address = this.addressFunction(this.deriveFunction(this.__parent, this.k + 1))
this.k += 1
this.map[address] = this.k
this.addresses.push(address)
return address
}
Chain.prototype.pop = function () {
var address = this.addresses.pop()
delete this.map[address]
this.k -= 1
return address
}
module.exports = Chain