-
Notifications
You must be signed in to change notification settings - Fork 0
/
head_tail.ts
31 lines (29 loc) · 1021 Bytes
/
head_tail.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Copyright © 2023 Tomoki Miyauchi. All rights reserved. MIT license.
// This module is browser compatible.
import type { Sequence } from "./types.ts";
/** Split the sequence into head and tail.
*
* @example
* ```ts
* import { headTail } from "https://deno.land/x/seqtools/head_tail.ts";
* import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
*
* assertEquals(headTail([1, 2, 3]), [1, [2, 3]]);
* assertEquals(headTail("abc"), ["a", "bc"]);
* assertEquals(headTail([]), [undefined, []]);
* ```
*/
export function headTail<const T, const U extends readonly unknown[]>(
array: readonly [T, ...U],
): [head: T, tail: U];
export function headTail<const T extends string, const U extends string>(
string: `${T}${U}`,
): [head: T, tail: U];
export function headTail<T, U = T>(
seq: Readonly<Sequence<T, U>>,
): [head: T | undefined, tail: U];
export function headTail<T, U = T>(
seq: Readonly<Sequence<T, U>>,
): [head: T | undefined, tail: U] {
return [seq.at(0), seq.slice(1)];
}