Delta encoding a list of numbers
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.