UNPKG

2.82 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 ********************************************************************************/
17//@flow
18
19type Defer<T> = {
20 promise: Promise<T>,
21 resolve: (T) => void,
22 reject: (any) => void,
23};
24
25export function defer<T>(): Defer<T> {
26 let resolve, reject;
27 let promise = new Promise(function (success, failure) {
28 resolve = success;
29 reject = failure;
30 });
31 if (!resolve || !reject) throw "defer() error"; // this never happens and is just to make flow happy
32 return { promise, resolve, reject };
33}
34
35// TODO use bip32-path library
36export function splitPath(path: string): number[] {
37 let result = [];
38 let components = path.split("/");
39 components.forEach((element) => {
40 let number = parseInt(element, 10);
41 if (isNaN(number)) {
42 return; // FIXME shouldn't it throws instead?
43 }
44 if (element.length > 1 && element[element.length - 1] === "'") {
45 number += 0x80000000;
46 }
47 result.push(number);
48 });
49 return result;
50}
51
52// TODO use async await
53
54export function eachSeries<A>(arr: A[], fun: (A) => Promise<*>): Promise<*> {
55 return arr.reduce((p, e) => p.then(() => fun(e)), Promise.resolve());
56}
57
58export function foreach<T, A>(
59 arr: T[],
60 callback: (T, number) => Promise<A>
61): Promise<A[]> {
62 function iterate(index, array, result) {
63 if (index >= array.length) {
64 return result;
65 } else
66 return callback(array[index], index).then(function (res) {
67 result.push(res);
68 return iterate(index + 1, array, result);
69 });
70 }
71 return Promise.resolve().then(() => iterate(0, arr, []));
72}
73
74export function doIf(
75 condition: boolean,
76 callback: () => any | Promise<any>
77): Promise<void> {
78 return Promise.resolve().then(() => {
79 if (condition) {
80 return callback();
81 }
82 });
83}
84
85export function asyncWhile<T>(
86 predicate: () => boolean,
87 callback: () => Promise<T>
88): Promise<Array<T>> {
89 function iterate(result) {
90 if (!predicate()) {
91 return result;
92 } else {
93 return callback().then((res) => {
94 result.push(res);
95 return iterate(result);
96 });
97 }
98 }
99 return Promise.resolve([]).then(iterate);
100}