Skip to content

Commit

Permalink
feat: add NonEmptyArray and specialized implementation of last()
Browse files Browse the repository at this point in the history
  • Loading branch information
spawnia committed Nov 26, 2021
1 parent 0c302fc commit 5f61c48
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
41 changes: 40 additions & 1 deletion src/array.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,31 @@
import { containSameValues, insertIf, withoutIndex } from './array';
import {
containSameValues,
insertIf,
isNonEmptyArray,
last,
NonEmptyArray,
withoutIndex,
} from './array';

describe('NonEmptyArray', () => {
it('can be proven to be non-empty', () => {
const array = [1];

// @ts-expect-error intentionally wrong
let nonEmptyArray: NonEmptyArray<unknown> = [];

// @ts-expect-error intentionally wrong
nonEmptyArray = array;

if (isNonEmptyArray(array)) {
nonEmptyArray = array;
}

expect(isNonEmptyArray(nonEmptyArray)).toBe(true);
expect(isNonEmptyArray([undefined])).toBe(true);
expect(isNonEmptyArray([])).toBe(false);
});
});

describe('withoutIndex', () => {
it('handles empty arrays', () => {
Expand Down Expand Up @@ -40,3 +67,15 @@ describe('insertIf', () => {
expect(insertIf(false, 1, 2)).toEqual([]);
});
});

describe('last', () => {
it('returns the last element of an array', () => {
const array: NonEmptyArray<number> = [1, 2];
const actual: number = last(array);
expect(actual).toEqual(2);
});

it('returns undefined for empty arrays', () => {
expect(last([])).toEqual(undefined);
});
});
13 changes: 13 additions & 0 deletions src/array.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { isEqual, sortBy } from 'lodash';

export type NonEmptyArray<T> = Array<T> & { 0: T };

export function isNonEmptyArray<T>(value: Array<T>): value is NonEmptyArray<T> {
return value.length > 0;
}

/**
* Return a new array that does not contain the item at the specified index.
*/
Expand Down Expand Up @@ -39,3 +45,10 @@ export function insertIf<T>(
): Array<T> {
return condition ? elements : [];
}

export function last<T, A extends Array<T>>(
array: A,
): A extends NonEmptyArray<T> ? T : T | undefined {
// @ts-expect-error too magical
return array[array.length - 1];
}

0 comments on commit 5f61c48

Please sign in to comment.