diff --git a/src/utils.js b/src/utils.js new file mode 100644 index 0000000..6cfa868 --- /dev/null +++ b/src/utils.js @@ -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)); +} diff --git a/src/utils.test.js b/src/utils.test.js new file mode 100644 index 0000000..04bef11 --- /dev/null +++ b/src/utils.test.js @@ -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); + }); +});