diff --git a/src/array/getClosestNumber.ts b/src/array/getClosestNumber.ts index afdfe24..f2bcf69 100644 --- a/src/array/getClosestNumber.ts +++ b/src/array/getClosestNumber.ts @@ -13,6 +13,8 @@ export function getClosestNumberInArray( input: number, array: number[], ): number { + if (input === null || input === undefined || array.length < 1) return 0 + return array.reduce((a, b) => Math.abs(b - input) < Math.abs(a - input) ? b : a, ) diff --git a/tests/array/closestNumber.test.ts b/tests/array/closestNumber.test.ts index ddd52ee..1223efa 100644 --- a/tests/array/closestNumber.test.ts +++ b/tests/array/closestNumber.test.ts @@ -1,16 +1,31 @@ import { describe, expect, it } from "vitest" import { getClosestNumberInArray } from "../../src" -import { n } from "vitest/dist/reporters-2ff87305" describe("closestNumberInArray", () => { it("should return the closest value", () => { const data: [number, number[], number][] = [ + [-100, [], 0], + [null, [10, 20], 0], + [undefined, [], 0], + + [-1, [-100, 0, 0.25, 0.5, 0.75, 1], 0], + [-51, [-100, 0, 0.25, 0.5, 0.75, 1], -100], [0.2, [0, 0.25, 0.5, 0.75, 1], 0.25], - // TODO other examples - [0.2, [0, 0.25, 0.5, 0.75, 1], 0.25], - [0.2, [0, 0.25, 0.5, 0.75, 1], 0.25], + + [-12, [-20, -10, 0, 10, 20], -10], + [-15, [-20, -10, 0, 10, 20], -20], + [-18, [-20, -10, 0, 10, 20], -20], + [0, [-20, -10, 0, 10, 20], 0], + [12, [-20, -10, 0, 10, 20], 10], + [15, [-20, -10, 0, 10, 20], 10], + [18, [-20, -10, 0, 10, 20], 20], + + [375, [100, 200, 300, 400, 500], 400], + [-100, [100, 200, 300, 400, 500], 100], + [100, [-100, -200, -300, -400, -500], -100], + [-375, [-100, -200, -300, -400, -500], -400], ] for (let [input, array, result] of data) {