on f83b9a5 help sign in
bridge/src/lib/lib.js
57 lines 1.3 kB history raw
1import 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 strSplice = (arr, i, val) => `${arr.slice(0, i)}${val}${arr.slice(i)}`;
21const isValidGalaxy = name => {
22 let point;
23 try {
24 point = patp2dec(name);
25 } catch (err) {
26 return false;
27 }
28 return point >= 0 && point < 256;
29};
31const randomPatq = len => {
32 let bytes = window.crypto.getRandomValues(new Uint8Array(len));
33 let hex = bytes.reduce(
34 (acc, byt) => acc + byt.toString(16).padStart(2, '0'),
35 ''
36 );
37 return ob.hex2patq(hex);
38};
40// TODO: is there a function for this calculation in urbit-ob or similar?
41// 3 characters per byte, plus a tilde and hypen prefix per pair of bytes
42const patpStringLength = byteLength =>
43 byteLength * 3 + Math.ceil(byteLength / 2);
45export {
46 compose,
47 allFalse,
48 isLast,
49 isUndefined,
50 defaultTo,
51 seq,
52 fill,
53 strSplice,
54 isValidGalaxy,
55 randomPatq,
56 patpStringLength,
57};