From a43067b2481707992cd6530d9e9c15462fe879a2 Mon Sep 17 00:00:00 2001 From: Thomas Reynolds Date: Tue, 3 Mar 2020 18:11:48 -0800 Subject: [PATCH] feat(core): add index, nth and last helpers --- src/__tests__/index.spec.ts | 11 +++++++++++ src/__tests__/last.spec.ts | 11 +++++++++++ src/__tests__/nth.spec.ts | 11 +++++++++++ src/index.ts | 8 +++++++- 4 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 src/__tests__/index.spec.ts create mode 100644 src/__tests__/last.spec.ts create mode 100644 src/__tests__/nth.spec.ts diff --git a/src/__tests__/index.spec.ts b/src/__tests__/index.spec.ts new file mode 100644 index 0000000..163c531 --- /dev/null +++ b/src/__tests__/index.spec.ts @@ -0,0 +1,11 @@ +import { index } from "../index" + +describe("index", () => { + test("gets the index item in an array", () => { + expect(index(0)([0, 1])).toBe(0) + }) + + test("gets the index item in an empty array", () => { + expect(index(0)([])).toBe(undefined) + }) +}) diff --git a/src/__tests__/last.spec.ts b/src/__tests__/last.spec.ts new file mode 100644 index 0000000..cd3f75f --- /dev/null +++ b/src/__tests__/last.spec.ts @@ -0,0 +1,11 @@ +import { last } from "../index" + +describe("last", () => { + test("gets the last item in an array", () => { + expect(last([0, 1])).toBe(1) + }) + + test("gets the last item in an empty array", () => { + expect(last([])).toBe(undefined) + }) +}) diff --git a/src/__tests__/nth.spec.ts b/src/__tests__/nth.spec.ts new file mode 100644 index 0000000..cfb01d2 --- /dev/null +++ b/src/__tests__/nth.spec.ts @@ -0,0 +1,11 @@ +import { nth } from "../index" + +describe("nth", () => { + test("gets the nth item in an array", () => { + expect(nth(1)([0, 1])).toBe(0) + }) + + test("gets the nth item in an empty array", () => { + expect(nth(1)([])).toBe(undefined) + }) +}) diff --git a/src/index.ts b/src/index.ts index 4fc6937..58754c6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,11 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -export const first = (items: T[]): T => items[0] +export const index = (i: number) => (items: T[]): T => items[i] + +export const nth = (n: number) => index(n - 1) + +export const first = index(0) + +export const last = (items: T[]): T => items[items.length - 1] export const constant = (value: T) => () => value