UNPKG

2.5 kBJavaScriptView Raw
1/********************************************************************************
2 * Ledger Node JS API
3 * (c) 2016-2017 Ledger
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 ********************************************************************************/
17export function defer() {
18 let resolve, reject;
19 let promise = new Promise(function (success, failure) {
20 resolve = success;
21 reject = failure;
22 });
23 if (!resolve || !reject) throw "defer() error"; // this never happens and is just to make flow happy
24
25 return {
26 promise,
27 resolve,
28 reject
29 };
30} // TODO use bip32-path library
31
32export function splitPath(path) {
33 let result = [];
34 let components = path.split("/");
35 components.forEach(element => {
36 let number = parseInt(element, 10);
37
38 if (isNaN(number)) {
39 return; // FIXME shouldn't it throws instead?
40 }
41
42 if (element.length > 1 && element[element.length - 1] === "'") {
43 number += 0x80000000;
44 }
45
46 result.push(number);
47 });
48 return result;
49} // TODO use async await
50
51export function eachSeries(arr, fun) {
52 return arr.reduce((p, e) => p.then(() => fun(e)), Promise.resolve());
53}
54export function foreach(arr, callback) {
55 function iterate(index, array, result) {
56 if (index >= array.length) {
57 return result;
58 } else return callback(array[index], index).then(function (res) {
59 result.push(res);
60 return iterate(index + 1, array, result);
61 });
62 }
63
64 return Promise.resolve().then(() => iterate(0, arr, []));
65}
66export function doIf(condition, callback) {
67 return Promise.resolve().then(() => {
68 if (condition) {
69 return callback();
70 }
71 });
72}
73export function asyncWhile(predicate, callback) {
74 function iterate(result) {
75 if (!predicate()) {
76 return result;
77 } else {
78 return callback().then(res => {
79 result.push(res);
80 return iterate(result);
81 });
82 }
83 }
84
85 return Promise.resolve([]).then(iterate);
86}
87//# sourceMappingURL=utils.js.map
\No newline at end of file