Created
December 9, 2019 10:58
-
-
Save cahnory/a7164411f742560b9406fe41aef4f125 to your computer and use it in GitHub Desktop.
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
export const closestToZero = input => { | |
if (!(Array.isArray(input) && input.length)) { | |
return 0; | |
} | |
return input.reduce((prev, value) => { | |
const ratio = Math.abs(prev / value); | |
if (ratio > 1 || (ratio === 1 && value > 0)) { | |
return value; | |
} | |
return prev; | |
}, Infinity); | |
}; |
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
import { closestToZero } from './index'; | |
describe('closestToZero', () => { | |
it('returns the value closest to 0', () => { | |
expect(closestToZero([8, 5, 10])).toEqual(5); | |
expect(closestToZero([8, -5, 10])).toEqual(-5); | |
}); | |
it('favours positive values', () => { | |
expect(closestToZero([8, 5, -5, 10])).toEqual(5); | |
expect(closestToZero([8, -5, 5, 10])).toEqual(5); | |
}); | |
it('returns 0 if input is not an array or is empty', () => { | |
expect(closestToZero([])).toEqual(0); | |
expect(closestToZero({})).toEqual(0); | |
expect(closestToZero(null)).toEqual(0); | |
expect(closestToZero()).toEqual(0); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment