Skip to content

Instantly share code, notes, and snippets.

@richardscarrott
Created January 24, 2020 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardscarrott/b2d1a89605c71782f4440054f261e911 to your computer and use it in GitHub Desktop.
Save richardscarrott/b2d1a89605c71782f4440054f261e911 to your computer and use it in GitHub Desktop.
closest([1, 2, 6, 0], 5) // 6
const closest = (values: number[], val: number) => {
if (!values.length) {
throw new VError(
{ info: { values, val } },
'Expected values to contain at least one value'
);
}
return values.reduce(
(acc, currVal) =>
Math.abs(acc.delta) > Math.abs(currVal - val)
? { closestVal: currVal, delta: currVal - val }
: acc,
{ closestVal: values[0], delta: values[0] - val }
).closestVal;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment