Skip to content

Commit

Permalink
feat(head): add head function
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Jun 29, 2023
1 parent 2e6dd84 commit 024d0f7
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
23 changes: 23 additions & 0 deletions head.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright © 2023 Tomoki Miyauchi. All rights reserved. MIT license.
// This module is browser compatible.

import type { Indexable } from "./types.ts";

/** Extract the first element of a sequence.
*
* @example
* ```ts
* import { head } from "https://deno.land/x/seqtools/head.ts";
* import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
*
* assertEquals(head([1, 2, 3]), 1);
* assertEquals(head("abc"), "a");
* assertEquals(head([]), undefined);
* ```
*/
export function head<const T>(seq: readonly [T, ...readonly unknown[]]): T;
export function head<T extends string>(seq: `${T}${string}`): T;
export function head<T>(seq: Indexable<T>): T | undefined;
export function head<T>(seq: Indexable<T>): T | undefined {
return seq[0];
}
66 changes: 66 additions & 0 deletions head_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright © 2023 Tomoki Miyauchi. All rights reserved. MIT license.

import { head } from "./head.ts";
import { Indexable } from "./types.ts";
import {
assertEquals,
assertType,
describe,
IsExact,
it,
} from "./_dev_deps.ts";

describe("head", () => {
it("should return first element", () => {
const table: [Indexable<unknown>, unknown][] = [
[[""], ""],
[[,], undefined],
[["a", "b", "c"], "a"],
["a", "a"],
["abc", "a"],

[[], undefined],
["", undefined],
];

table.forEach(([seq, expected]) => {
assertEquals(head(seq), expected);
});
});

it("should infer undefined if empty array", () => {
const result = head([]);
assertType<IsExact<typeof result, undefined>>(true);
});

it("should infer undefined or string if empty string", () => {
const result = head("");
assertType<IsExact<typeof result, undefined | string>>(true);
});

it("should infer string or undefined if array", () => {
const result = head([] as string[]);
assertType<IsExact<typeof result, string | undefined>>(true);
});

it("should infer string or undefined if string", () => {
const result = head("" as string);
assertType<IsExact<typeof result, string | undefined>>(true);
});

it("should infer first element if tuple", () => {
const result = head([""]);
assertType<IsExact<typeof result, "">>(true);

const result2 = head(["a", "b", "c"]);
assertType<IsExact<typeof result2, "a">>(true);
});

it("should infer first element if template string literal", () => {
const result = head("a");
assertType<IsExact<typeof result, "a">>(true);

const result2 = head("abc");
assertType<IsExact<typeof result2, "a">>(true);
});
});

0 comments on commit 024d0f7

Please sign in to comment.