Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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