Added at, first and last

This commit is contained in:
Michaël Lemaire 2019-10-22 22:07:18 +02:00
parent 9479b61c09
commit 67292dd0b8
4 changed files with 73 additions and 2 deletions

View file

@ -44,6 +44,17 @@ n(1) // => false
n(2) // => true
```
**at** gets an array's item by position:
```typescript
const getthird = at(2);
getthird([2, 4, 8, 16]); // => 8
getthird([2, 4]); // => undefined
const getsecondlast = at(-2);
getsecondlast([1, 2, 3, 4]); // => 3
getsecondlast([1]); // => undefined
```
**attr** gets an object's attribute:
```typescript
@ -80,6 +91,15 @@ bool({x: 1}); // => true
[-2, 8, -7].sort(cmp({ key: Math.abs })) // => [-2, -7, 8]
```
**first** and **last** return the first or last item of an array:
```typescript
first([1, 2, 3]) // => 1
first([]) // => undefined
last([1, 2, 3]) // => 3
last([]) // => undefined
```
**identity** returns its argument untouched:
```typescript

View file

@ -1,6 +1,6 @@
{
"name": "tk-functional",
"version": "0.2.1",
"version": "0.2.2",
"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, attr, bool, cmp, fmap, identity, is, isinstance, 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 } from "./index";
describe(nop, () => {
it("does nothing", () => {
@ -136,6 +136,36 @@ describe(attr, () => {
});
});
describe(at, () => {
it("gets an index in an array", () => {
const second = at(1);
expect(second([1, 4, 8])).toBe(4);
expect(second([1])).toBeUndefined();
});
it("handles negative indices from the end", () => {
const second_from_end = at(-2);
expect(second_from_end([1, 4, 6, 8])).toBe(6);
expect(second_from_end([1])).toBeUndefined();
});
});
describe(first, () => {
it("gets the first item in an array", () => {
expect(first([1, 4, 8])).toBe(1);
expect(first([1])).toBe(1);
expect(first([])).toBeUndefined();
});
});
describe(last, () => {
it("gets the last item in an array", () => {
expect(last([1, 4, 8])).toBe(8);
expect(last([1])).toBe(1);
expect(last([])).toBeUndefined();
});
});
describe(nn, () => {
it("checks for null", () => {
expect(nn(undefined)).toBeUndefined();

View file

@ -111,6 +111,27 @@ export function attr<K extends string>(name: K): <V, O extends Record<K, V>>(obj
return obj => obj[name];
}
/**
* Index getter
*/
export function at<T>(idx: number): (array: ReadonlyArray<T>) => T | undefined {
if (idx < 0) {
return array => array[array.length + idx];
} else {
return array => array[idx];
}
}
/**
* Array first item getter
*/
export const first: <T>(array: ReadonlyArray<T>) => T | undefined = at(0);
/**
* Array last item getter
*/
export const last: <T>(array: ReadonlyArray<T>) => T | undefined = at(-1);
/**
* Check that a value is not null, throwing an error if it is
*/