Skip to content

Instantly share code, notes, and snippets.

@nfroidure
Created August 3, 2018 11:29
Show Gist options
  • Save nfroidure/08432a4d6994eefffb0dd319aade462c to your computer and use it in GitHub Desktop.
Save nfroidure/08432a4d6994eefffb0dd319aade462c to your computer and use it in GitHub Desktop.
function buildMessage(values) {
const DIFF = Math.pow(2, 9); // 512
const MAX_PRECISION = 4; // 512 * 4 allows to encode 300 <= x <= 1100
const maxIndex = values.indexOf(Math.max(...values));
const minIndex = values.indexOf(Math.min(...values));
const maxDiff = values.reduce(
(diff, v) => Math.max(v - values[minIndex], diff),
0
);
const precision = Math.ceil(maxDiff / DIFF);
if (precision > MAX_PRECISION) {
throw new Error('Cannot encode to that precision' + precision);
}
return JSON.stringify({
min: Math.round(values[minIndex]),
maxDiff: Math.round((values[maxIndex] - values[minIndex]) / precision),
leftDiffs:
values
.filter((v, index) => index !== maxIndex && index !== minIndex)
.map(v => Math.round(v - values[minIndex])),
precision, // 1 or 2 bits
minIndex, // max values.length bits
maxIndex, // max values.length bits
}, null, 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment