-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.ts
33 lines (29 loc) · 1.12 KB
/
init.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
32
33
// Copyright © 2023 Tomoki Miyauchi. All rights reserved. MIT license.
// This module is browser compatible.
import type { Sliceable } from "./types.ts";
/** Extract the elements before the last of a sequence.
*
* @example
* ```ts
* import { init } from "https://deno.land/x/seqtools/init.ts";
* import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
*
* assertEquals(init([1, 2, 3]), [1, 2]);
* assertEquals(init("abc"), "ab");
* assertEquals(init([0]), []);
* assertEquals(init([]), []);
* ```
*/
export function init<const T extends readonly unknown[]>(
array: readonly [...T, unknown],
): T;
export function init<const T extends string>(string: `${T}`): InitString<T>;
export function init<T>(seq: Readonly<Sliceable<T>>): T;
export function init<T>(seq: Readonly<Sliceable<T>>): T {
return seq.slice(0, -1);
}
/** Infer the string without last character. */
export type InitString<T extends string> = T extends "" ? "" : DropLastChar<T>;
type DropLastChar<T extends string, Acc extends string = ""> = T extends
`${infer U}${infer V}` ? V extends "" ? Acc : DropLastChar<V, `${Acc}${U}`>
: never;