forked from ethereumjs/merkle-patricia-tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
78 lines (70 loc) · 1.68 KB
/
util.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
const async = require('async')
module.exports = {
matchingNibbleLength: matchingNibbleLength,
callTogether: callTogether,
asyncFirstSeries: asyncFirstSeries,
doKeysMatch: doKeysMatch
}
/**
* Returns the number of in order matching nibbles of two give nibble arrayes
* @method matchingNibbleLength
* @param {Array} nib1
* @param {Array} nib2
*/
function matchingNibbleLength (nib1, nib2) {
var i = 0
while (nib1[i] === nib2[i] && nib1.length > i) {
i++
}
return i
}
/**
* Compare two 'nibble array' keys
*/
function doKeysMatch (keyA, keyB) {
var length = matchingNibbleLength(keyA, keyB)
return length === keyA.length && length === keyB.length
}
/**
* Take two or more functions and returns a function that will execute all of
* the given functions
*/
function callTogether () {
var funcs = arguments
var length = funcs.length
var index = length
if (!length) {
return function () {}
}
return function () {
length = index
while (length--) {
var fn = funcs[length]
if (typeof fn === 'function') {
var result = funcs[length].apply(this, arguments)
}
}
return result
}
}
/**
* Take a collection of async fns, call the cb on the first to return a truthy value.
* If all run without a truthy result, return undefined
*/
function asyncFirstSeries (array, iterator, cb) {
var didComplete = false
async.eachSeries(array, function (item, next) {
if (didComplete) return next
iterator(item, function (err, result) {
if (result) {
didComplete = true
process.nextTick(cb.bind(null, null, result))
}
next(err)
})
}, function () {
if (!didComplete) {
cb()
}
})
}