Skip to content

Commit

Permalink
Add array utils
Browse files Browse the repository at this point in the history
  • Loading branch information
pomber committed Mar 3, 2019
1 parent 0f88685 commit 0e26743
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function nextIndex(list, currentIndex) {
return Math.min(list.length - 1, Math.floor(currentIndex + 1));
}

export function prevIndex(list, currentIndex) {
return Math.max(0, Math.ceil(currentIndex - 1));
}
29 changes: 29 additions & 0 deletions src/utils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { nextIndex, prevIndex } from "./utils";

describe("nextIndex", () => {
const fiveItems = [1, 2, 3, 4, 5];
test("works with middle index", () => {
expect(nextIndex(fiveItems, 2)).toBe(3);
});
test("works with last index", () => {
expect(nextIndex(fiveItems, 4)).toBe(4);
});
test("works with fractions", () => {
expect(nextIndex(fiveItems, 1.1)).toBe(2);
expect(nextIndex(fiveItems, 1.9)).toBe(2);
});
});

describe("prevIndex", () => {
const fiveItems = [1, 2, 3, 4, 5];
test("works with middle index", () => {
expect(prevIndex(fiveItems, 2)).toBe(1);
});
test("works with start index", () => {
expect(prevIndex(fiveItems, 0)).toBe(0);
});
test("works with fractions", () => {
expect(prevIndex(fiveItems, 1.1)).toBe(1);
expect(prevIndex(fiveItems, 1.9)).toBe(1);
});
});

0 comments on commit 0e26743

Please sign in to comment.