Improved "first" typing for tuples

This commit is contained in:
Michaël Lemaire 2019-10-22 22:24:45 +02:00
parent 67292dd0b8
commit c446fb7840
4 changed files with 30 additions and 4 deletions

2
package-lock.json generated
View file

@ -1,6 +1,6 @@
{
"name": "tk-functional",
"version": "0.1.5",
"version": "0.2.3",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View file

@ -1,6 +1,6 @@
{
"name": "tk-functional",
"version": "0.2.2",
"version": "0.2.3",
"description": "Typescript/Javascript helpers for functional-style programming",
"source": "src/index.ts",
"main": "dist/tk-functional.umd.js",

View file

@ -1,4 +1,4 @@
import { always, and, at, attr, bool, cmp, first, fmap, identity, is, isinstance, last, never, nn, nnu, nop, not, nu, or, partial, pipe } from "./index";
import { always, and, at, attr, bool, cmp, first, fmap, identity, is, isinstance, last, never, nn, nnu, nop, not, nu, or, partial, pipe, second, third } from "./index";
describe(nop, () => {
it("does nothing", () => {
@ -158,6 +158,22 @@ describe(first, () => {
});
});
describe(second, () => {
it("gets the second item in an array", () => {
expect(second([1, 4, 8])).toBe(4);
expect(second([1])).toBeUndefined();
expect(second([])).toBeUndefined();
});
});
describe(third, () => {
it("gets the third item in an array", () => {
expect(third([1, 4, 8])).toBe(8);
expect(third([1, 4])).toBeUndefined();
expect(third([])).toBeUndefined();
});
});
describe(last, () => {
it("gets the last item in an array", () => {
expect(last([1, 4, 8])).toBe(8);

View file

@ -125,7 +125,17 @@ export function at<T>(idx: number): (array: ReadonlyArray<T>) => T | undefined {
/**
* Array first item getter
*/
export const first: <T>(array: ReadonlyArray<T>) => T | undefined = at(0);
export const first: <T extends ReadonlyArray<any>>(array: T) => T[0] | undefined = at(0);
/**
* Array second item getter
*/
export const second: <T extends ReadonlyArray<any>>(array: T) => T[1] | undefined = at(1);
/**
* Array third item getter
*/
export const third: <T extends ReadonlyArray<any>>(array: T) => T[2] | undefined = at(2);
/**
* Array last item getter