How to convert a hexadecimal string to Uint8Array and back in JavaScript?

Vanilla JS: const fromHexString = (hexString) => Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); const toHexString = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, ‘0’), ”); console.log(toHexString(Uint8Array.from([0, 1, 2, 42, 100, 101, 102, 255]))); console.log(fromHexString(‘0001022a646566ff’)); Note: this method trusts its input. If the provided input has a length of 0, an error will be thrown. If the … Read more

RxJS Promise Composition (passing data)

I did not read all of it, but if you want to achieve the same as pl().then(p2).then(p3).then(console.log);, with p being function returning promises, you could do something like (example here) Rx.Observable.fromPromise(p1()) .flatMap(function(p1_result){return p2(p1_result);}) .flatMap(function(p2_result){return p3(p2_result);}) Or the more symmetric : var chainedPromises$ = Rx.Observable.just() .flatMap(p1) .flatMap(p2) .flatMap(p3); Now if you want to execute sequentially callback … Read more

Sort an array of objects based on another array of ids

You can provide a custom comparison function to JavaScript’s Array#sort method. Use the custom comparison function to ensure the sort order: var sortOrder = [2,3,1,4], items = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]; items.sort(function (a, b) { return sortOrder.indexOf(a.id) – sortOrder.indexOf(b.id); }); MDN: If compareFunction(a, b) returns less than 0, sort a to … Read more