Given a list of numbers, e.g.:25626 25757 24367 24267 16 100 2 7277Output a delta encoding for the sequence. In a delta encoding, the firstelement is reproduced as is. Each subsequent element is represented as thenumeric difference from the element before it. E.g. for the sequence above,the delta encoding would be:25626 131 -1390 -100 -24251 84 -98 7275However, if a difference value does not fit in a single signed byte,i.e. -127 <= x <= 127, then, instead of the difference, we would liketo use an escape token, printing it.This will denote that the value following the escape token is a fullfour-byte difference value, rather than a one-byte different value.For this exercise, we'll declare -128 as the escape token.Following the same example above, the final result would be:25626 -128 131 -128 -1390 -100 -128 -24251 84 -98 -128 7275function getDelta(arr) {  let diffs = [];  for (let i = 1, N = arr.length -1; i <= N; ++i) {    diffs.push(arr[i] - arr[i - 1]);  }   return diffs;}function encode(arr) {  if (arr.length === 0) {    return arr;  }  let encoding = [];  let deltas = getDelta(arr);  for (let delta of deltas) {    if (127 < delta || delta < -127) {      encoding.push(-128);    }    encoding.push(delta);  }  encoding.unshift(arr[0]);  return encoding;}console.log(encode('25626'.split(' ')).join(' '));console.log(encode('25626 25757 24367 24267 16 100 2 7277'.split(' ')).join(' '));
Delta encoding a list of numbers
javascript;performance;algorithm;programming challenge
Another option is to iterate over the array of values using Array.reduce.  For me this makes its purpose more apparent.  Also it naturally handles a zero length array.function encode(values) {  return values.reduce(_computeDiff, {    encoded: []  }).encoded;}Here the initial accumulator value is a state value that contains the encoded output.  It will also be used to hold the lastValue.  The _computeDiff function can then update the state for each value.function _computeDiff(state, value) {  // lastValue initially undefined will produce diff NaN  let diff = value - state.lastValue;  // insert escape code for large differences  if (Math.abs(diff) > 127) {    state.encoded.push(-128);  }  state.encoded.push(isNaN(diff) ? value : diff);  state.lastValue = value;  return state;}This does rely on the fact that a math operation on an undefined value is NaN. Also it uses Math.abs to more succinctly describe the escape threshold.