Skip to content

Instantly share code, notes, and snippets.

@kayac-chang
Created January 31, 2022 10:01
Show Gist options
  • Save kayac-chang/9335cadee7270dce6cf50f4a1e08756e to your computer and use it in GitHub Desktop.
Save kayac-chang/9335cadee7270dce6cf50f4a1e08756e to your computer and use it in GitHub Desktop.
[learn FP with Kirby using `fp-ts`] Array
/**
* Array
* ===
* Basic array
*/
import { pipe } from "fp-ts/lib/function";
import * as Array from "fp-ts/Array";
const foo = [1, 2, 3, 4, 5];
describe("array support basic operation like js array", () =>
pipe(
foo,
Array.map((x) => x - 1),
Array.filter((x) => x % 2 === 0),
Array.reduce(0, (a, b) => a + b)
));
/**
* lookup
* ===
* lookup provide array element access but with type safety
*/
import { pipe } from "fp-ts/function";
import * as Array from "fp-ts/Array";
const foo = [1, 2, 3];
describe("lookup item which exist", () =>
pipe(
foo,
Array.lookup(1)
//
)); // { _tag: 'Some', value: 2 }
describe("lookup item which not exist", () =>
pipe(
foo,
Array.lookup(3)
//
)); // { _tag: 'None' }
/**
* Because it returns an Option, we are forced to deal with the possible none case.
*/
/**
* head
* ===
* get the first element with option
*/
describe("head get the first element if array not empty", () => {
const foo = [1, 2, 3];
if (foo.length > 0) {
const firstElement = Array.head(foo); // { _tag: 'Some', value: 1 }
}
});
import * as NEA from "fp-ts/NonEmptyArray";
describe("NonEmptyArray head get first element without option", () => {
if (Array.isNonEmpty(foo)) {
const firstElement = NEA.head(foo); // 1
}
});
/**
* zip
* ===
* combine two array into one
*/
import { pipe } from "fp-ts/function";
import * as Array from "fp-ts/Array";
const foo = [1, 2, 3, 4, 5];
const bar = ["a", "b", "c", "d", "e"];
describe("array provide additional function like 'zip'", () =>
pipe(
foo,
Array.zip(bar)
//
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment