Delta encoding a list of numbers Given a list of numbers, e.g.:

25626 25757 24367 24267 16 100 2 7277

Output a delta encoding for the sequence. In a delta encoding, the first
element is reproduced as is. Each subsequent element is represented as the
numeric difference from the element before it. E.g. for the sequence above,
the delta encoding would be:

25626 131 -1390 -100 -24251 84 -98 7275

However, if a difference value does not fit in a single signed byte,
i.e. -127 &lt;= x &lt;= 127, then, instead of the difference, we would like
to use an escape token, printing it.

This will denote that the value following the escape token is a full
four-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 7275

function getDelta(arr) {
  let diffs = [];
  for (let i = 1, N = arr.length -1; i &lt;= 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 &lt; delta || delta &lt; -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(' '));
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) &gt; 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.