Created
January 24, 2020 12:23
-
-
Save richardscarrott/b2d1a89605c71782f4440054f261e911 to your computer and use it in GitHub Desktop.
closest([1, 2, 6, 0], 5) // 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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