Skip to content

Commit

Permalink
Added some tests and improved function
Browse files Browse the repository at this point in the history
  • Loading branch information
theoplawinski committed Nov 20, 2023
1 parent 69020b4 commit 357a873
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
2 changes: 2 additions & 0 deletions src/array/getClosestNumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down
23 changes: 19 additions & 4 deletions tests/array/closestNumber.test.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down

0 comments on commit 357a873

Please sign in to comment.