on 21d1c95 help sign in
bridge/src/lib/lib.js
54 lines 1.2 kB history raw
1import * as ob from 'urbit-ob';
2import patp2dec from './patp2dec';
4const compose = (...fs) =>
5 fs.reduceRight((pF, nF) => (...args) => nF(pF(...args)), v => v);
7const allFalse = (...args) => args.every(a => a === false);
9const isLast = (l, i) => i === l - 1;
11const isUndefined = v => v === undefined;
13const defaultTo = (v, d) => (isUndefined(v) ? d : v);
15const seq = n => Array.from(Array(n), (_, i) => i);
17const fill = (n, v) => Array.from(Array(n), () => v);
19const isValidGalaxy = name => {
20 let point;
21 try {
22 point = patp2dec(name);
23 } catch (err) {
24 return false;
25 }
26 return point >= 0 && point < 256;
27};
29const randomPatq = len => {
30 let bytes = window.crypto.getRandomValues(new Uint8Array(len));
31 let hex = bytes.reduce(
32 (acc, byt) => acc + byt.toString(16).padStart(2, '0'),
33 ''
34 );
35 return ob.hex2patq(hex);
36};
38// TODO: is there a function for this calculation in urbit-ob or similar?
39// 3 characters per byte, plus a tilde and hypen prefix per pair of bytes
40const patpStringLength = byteLength =>
41 byteLength * 3 + Math.ceil(byteLength / 2);
43export {
44 compose,
45 allFalse,
46 isLast,
47 isUndefined,
48 defaultTo,
49 seq,
50 fill,
51 isValidGalaxy,
52 randomPatq,
53 patpStringLength,
54};