@bodil/core 0.5.8 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Assertions and predicates.
3
+ * @module
4
+ */
5
+ interface ImportMetaEnv {
6
+ DEV?: boolean;
7
+ }
8
+ declare global {
9
+ interface ImportMeta {
10
+ env?: ImportMetaEnv;
11
+ }
12
+ }
13
+ /**
14
+ * The specific {@link Error} type thrown by assertions.
15
+ */
16
+ export declare class AssertionError extends Error {
17
+ }
18
+ /**
19
+ * Asserts that a condition is true. Throws an exception if it's not.
20
+ *
21
+ * When using Vite, this function generates no code when building a production
22
+ * bundle.
23
+ *
24
+ * @example
25
+ * ```ts @import.meta.vitest
26
+ * assert(2 === 2);
27
+ * expect(() => assert(2 === 3)).toThrowError();
28
+ * ```
29
+ */
30
+ export declare function assert(assertion: unknown, message?: string): asserts assertion;
31
+ /**
32
+ * As {@link assert}, but isn't skipped in production.
33
+ */
34
+ export declare function assertAlways(assertion: unknown, message?: string): asserts assertion;
35
+ /**
36
+ * Throws an exception used to mark unreachable code.
37
+ */
38
+ export declare function unreachable(): never;
39
+ /**
40
+ * Assert that a type is `never` when type checking. Throws an
41
+ * {@link unreachable} exception if it's reached at runtime. This is meant as an
42
+ * exhaustiveness check.
43
+ *
44
+ * @example
45
+ * type State = "on" | "off";
46
+ * function checkState(state: State) {
47
+ * if (state === "on") {
48
+ * console.log("it's on");
49
+ * } else if (state === "off") {
50
+ * console.log("it's off");
51
+ * } else {
52
+ * // this would fail to type check if you
53
+ * // haven't tested all valid `State` values
54
+ * // in the above if statement:
55
+ * assertNever<typeof state>();
56
+ * }
57
+ * }
58
+ */
59
+ export declare function assertNever<T extends never>(_value: T): T;
60
+ /**
61
+ * Returns the given value unchanged if it's neither `null` nor `undefined`.
62
+ * Throws an exception otherwise.
63
+ */
64
+ export declare function present<A>(value: A, message?: string): NonNullable<A>;
65
+ /**
66
+ * Tests whether a value is `null`, `undefined`, `false`, an empty array or an
67
+ * empty string.
68
+ */
69
+ export declare function isEmpty(value: unknown): value is null | undefined | void | "" | [] | false;
70
+ /**
71
+ * Tests whether a value is `null` or `undefined`.
72
+ */
73
+ export declare function isNullish(value: unknown): value is null | undefined | void;
74
+ /**
75
+ * Tests whether a value is an {@link Iterable}.
76
+ */
77
+ export declare function isIterable(value: unknown): value is Iterable<unknown>;
78
+ /**
79
+ * Tests whether a value is an {@link AsyncIterable}.
80
+ */
81
+ export declare function isAsyncIterable(value: unknown): value is AsyncIterable<unknown>;
82
+ /**
83
+ * Compares two values for deep equality.
84
+ *
85
+ * Handles {@link Map}, {@link Set}, {@link ArrayBuffer}, {@link RegExp},
86
+ * {@link Equals} and objects with a `valueOf` or `toString` method in addition
87
+ * to the language built-ins.
88
+ *
89
+ * The implementation is a gently modified version of
90
+ * [fast-deep-equal](https://www.npmjs.com/package/fast-deep-equal).
91
+ */
92
+ export declare function isDeepEqual(a: unknown, b: unknown): boolean;
93
+ export {};
@@ -0,0 +1 @@
1
+ import "temporal-polyfill/global";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ /**
2
+ * A multi consumer event broadcaster, like an `EventTarget` but async and
3
+ * without named events.
4
+ */
5
+ export declare class Emitter<A> implements Disposable {
6
+ #private;
7
+ [Symbol.dispose](): void;
8
+ on(listener: (event: A) => void): Disposable;
9
+ emit(event: A): void;
10
+ }
@@ -0,0 +1,22 @@
1
+ import { defer } from "../async";
2
+ import { toDisposable } from "../disposable";
3
+ /**
4
+ * A multi consumer event broadcaster, like an `EventTarget` but async and
5
+ * without named events.
6
+ */
7
+ export class Emitter {
8
+ #listeners = new Set();
9
+ [Symbol.dispose]() {
10
+ this.#listeners.clear();
11
+ }
12
+ on(listener) {
13
+ this.#listeners.add(listener);
14
+ return toDisposable(() => this.#listeners.delete(listener));
15
+ }
16
+ emit(event) {
17
+ for (const listener of this.#listeners) {
18
+ defer(() => listener(event));
19
+ }
20
+ }
21
+ }
22
+ //# sourceMappingURL=emitter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emitter.js","sourceRoot":"","sources":["../../src/async/emitter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C;;;GAGG;AACH,MAAM,OAAO,OAAO;IACP,UAAU,GAAG,IAAI,GAAG,EAAsB,CAAC;IAEpD,CAAC,MAAM,CAAC,OAAO,CAAC;QACZ,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;IAC5B,CAAC;IAED,EAAE,CAAC,QAA4B;QAC3B,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC9B,OAAO,YAAY,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;IAChE,CAAC;IAED,IAAI,CAAC,KAAQ;QACT,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACrC,KAAK,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;QACjC,CAAC;IACL,CAAC;CACJ"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Async utilities.
3
+ * @module
4
+ */
5
+ export { AbortablePromise, type AbortableExecutor } from "./async/abortable-promise";
6
+ export { Emitter } from "./async/emitter";
7
+ /**
8
+ * Call the provided function at the soonest opportunity after the current task
9
+ * yields.
10
+ *
11
+ * This is implemented using {@link queueMicrotask}.
12
+ */
13
+ export declare function defer(fn: () => void | PromiseLike<void>): Disposable;
14
+ export type SchedulerAPI = {
15
+ schedule: (job: () => void) => Disposable;
16
+ };
17
+ export declare const SchedulerAPI: Record<string, SchedulerAPI>;
18
+ /**
19
+ * Return a promise that will resolve after the specified number of
20
+ * milliseconds or {@link Temporal.Duration}.
21
+ */
22
+ export declare function sleep(duration: number | Temporal.Duration): Promise<void>;
23
+ /**
24
+ * Test whether a value is an `AbortError`.
25
+ */
26
+ export declare function isAbortError(value: unknown): value is DOMException & {
27
+ name: "AbortError";
28
+ };
package/dist/async.js ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Async utilities.
3
+ * @module
4
+ */
5
+ import { idleCallback, timeout, toDisposable } from "./disposable";
6
+ export { AbortablePromise } from "./async/abortable-promise";
7
+ export { Emitter } from "./async/emitter";
8
+ /**
9
+ * Call the provided function at the soonest opportunity after the current task
10
+ * yields.
11
+ *
12
+ * This is implemented using {@link queueMicrotask}.
13
+ */
14
+ export function defer(fn) {
15
+ let disposed = false;
16
+ globalThis.queueMicrotask(() => {
17
+ if (disposed) {
18
+ return;
19
+ }
20
+ disposed = true;
21
+ fn();
22
+ });
23
+ return toDisposable(() => {
24
+ disposed = true;
25
+ });
26
+ }
27
+ // eslint-disable-next-line no-useless-assignment
28
+ export const SchedulerAPI = {
29
+ Microtask: {
30
+ schedule: defer,
31
+ },
32
+ Macrotask: {
33
+ schedule: globalThis.requestIdleCallback !== undefined
34
+ ? (f) => idleCallback(f)
35
+ : (f) => timeout(f, 0),
36
+ },
37
+ };
38
+ /**
39
+ * Return a promise that will resolve after the specified number of
40
+ * milliseconds or {@link Temporal.Duration}.
41
+ */
42
+ export function sleep(duration) {
43
+ return new Promise((resolve) => {
44
+ setTimeout(resolve, typeof duration === "number" ? duration : duration.total("milliseconds"));
45
+ });
46
+ }
47
+ /**
48
+ * Test whether a value is an `AbortError`.
49
+ */
50
+ export function isAbortError(value) {
51
+ return value instanceof DOMException && value.name === "AbortError";
52
+ }
53
+ //# sourceMappingURL=async.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async.js","sourceRoot":"","sources":["../src/async.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEnE,OAAO,EAAE,gBAAgB,EAA0B,MAAM,2BAA2B,CAAC;AACrF,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAE1C;;;;;GAKG;AACH,MAAM,UAAU,KAAK,CAAC,EAAkC;IACpD,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,UAAU,CAAC,cAAc,CAAC,GAAG,EAAE;QAC3B,IAAI,QAAQ,EAAE,CAAC;YACX,OAAO;QACX,CAAC;QACD,QAAQ,GAAG,IAAI,CAAC;QAChB,EAAE,EAAE,CAAC;IACT,CAAC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC,GAAG,EAAE;QACrB,QAAQ,GAAG,IAAI,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC;AAMD,iDAAiD;AACjD,MAAM,CAAC,MAAM,YAAY,GAAiC;IACtD,SAAS,EAAE;QACP,QAAQ,EAAE,KAAK;KAClB;IACD,SAAS,EAAE;QACP,QAAQ,EACJ,UAAU,CAAC,mBAAmB,KAAK,SAAS;YACxC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC;YACxB,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;KACjC;CACJ,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,KAAK,CAAC,QAAoC;IACtD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC3B,UAAU,CACN,OAAO,EACP,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,CAC3E,CAAC;IACN,CAAC,CAAC,CAAC;AACP,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,KAAc;IACvC,OAAO,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,CAAC;AACxE,CAAC"}
@@ -0,0 +1,45 @@
1
+ import { type Option } from "@bodil/opt";
2
+ /**
3
+ * Configuration for the {@link LFUCache}.
4
+ */
5
+ export type LFUCacheOptions<V> = {
6
+ /**
7
+ * The maximum size of the cache.
8
+ */
9
+ maxLength?: number;
10
+ /**
11
+ * An optional dispose function to be called when a value is removed from
12
+ * the cache. Defaults to disposing of values which implement
13
+ * {@link Disposable}, and doing nothing otherwise.
14
+ */
15
+ disposeFunction?: (value: V) => void;
16
+ };
17
+ /**
18
+ * A Least Frequently Used cache.
19
+ *
20
+ * When the cache needs to drop a value to stay within its bounds, it chooses
21
+ * the value that has the lowest access count.
22
+ */
23
+ export declare class LFUCache<K, V> implements Disposable {
24
+ #private;
25
+ constructor(options?: LFUCacheOptions<V>);
26
+ [Symbol.dispose](): void;
27
+ /**
28
+ * Get the current size of the cache.
29
+ */
30
+ get size(): number;
31
+ /**
32
+ * Test if the cache contains a given key.
33
+ *
34
+ * This does not count as an access towards cache invalidation.
35
+ */
36
+ has(key: K): boolean;
37
+ /**
38
+ * Get the value associated with the given key, if it exists in the cache.
39
+ */
40
+ get(key: K): Option<V>;
41
+ /**
42
+ * Add a key/value pair to the cache.
43
+ */
44
+ set(key: K, value: V): void;
45
+ }
@@ -0,0 +1 @@
1
+ import "@bodil/opt-vitest";
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Interface for nodes in a {@link LinkedList}.
3
+ */
4
+ export interface ListNode {
5
+ prev?: this;
6
+ next?: this;
7
+ }
8
+ /**
9
+ * A doubly linked list.
10
+ *
11
+ * You never know when you're going to need one.
12
+ */
13
+ export declare class LinkedList<Node extends ListNode> implements Iterable<Node> {
14
+ head?: Node;
15
+ tail?: Node;
16
+ /**
17
+ * Remove a node from the list.
18
+ */
19
+ remove(node: Node): void;
20
+ /**
21
+ * Insert a node into the list between the given nodes.
22
+ *
23
+ * It goes without saying that the `prev`/`next` nodes must be adjacent to
24
+ * each other in the list, or exceptions will be thrown.
25
+ */
26
+ insert(node: Node, prev?: Node, next?: Node): Node;
27
+ /**
28
+ * Insert a node at the head of the list.
29
+ */
30
+ pushHead(node: Node): void;
31
+ /**
32
+ * Insert a node at the tail of the list.
33
+ */
34
+ pushTail(node: Node): void;
35
+ /**
36
+ * Remove the node at the head of the list and return it.
37
+ */
38
+ popHead(): Node | undefined;
39
+ /**
40
+ * Remove the node at the tail of the list and return it.
41
+ */
42
+ popTail(): Node | undefined;
43
+ /**
44
+ * Iterate over the nodes in the list from head to tail.
45
+ */
46
+ [Symbol.iterator]: () => IterableIterator<Node>;
47
+ }
@@ -0,0 +1,45 @@
1
+ import { type Option } from "@bodil/opt";
2
+ /**
3
+ * Configuration for the {@link LRUCache}.
4
+ */
5
+ export type LRUCacheOptions<V> = {
6
+ /**
7
+ * The maximum size of the cache.
8
+ */
9
+ maxLength?: number;
10
+ /**
11
+ * An optional dispose function to be called when a value is removed from
12
+ * the cache. Defaults to disposing of values which implement
13
+ * {@link Disposable}, and doing nothing otherwise.
14
+ */
15
+ disposeFunction?: (value: V) => void;
16
+ };
17
+ /**
18
+ * A Least Recently Used cache.
19
+ *
20
+ * When the cache needs to drop a value to stay within its bounds, it chooses
21
+ * the value that was accessed the least recently.
22
+ */
23
+ export declare class LRUCache<K, V> implements Disposable {
24
+ #private;
25
+ constructor(options?: LRUCacheOptions<V>);
26
+ [Symbol.dispose](): void;
27
+ /**
28
+ * Get the current size of the cache.
29
+ */
30
+ get size(): number;
31
+ /**
32
+ * Test if the cache contains a given key.
33
+ *
34
+ * This does not count as an access towards cache invalidation.
35
+ */
36
+ has(key: K): boolean;
37
+ /**
38
+ * Get the value associated with the given key, if it exists in the cache.
39
+ */
40
+ get(key: K): Option<V>;
41
+ /**
42
+ * Add a key/value pair to the cache.
43
+ */
44
+ set(key: K, value: V): void;
45
+ }
@@ -0,0 +1 @@
1
+ import "@bodil/opt-vitest";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Some useful data structures.
3
+ * @module
4
+ */
5
+ export { LinkedList, type ListNode } from "./collections/linked-list";
6
+ export { LFUCache, type LFUCacheOptions } from "./collections/lfu-cache";
7
+ export { LRUCache, type LRUCacheOptions } from "./collections/lru-cache";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Some useful data structures.
3
+ * @module
4
+ */
5
+ export { LinkedList } from "./collections/linked-list";
6
+ export { LFUCache } from "./collections/lfu-cache";
7
+ export { LRUCache } from "./collections/lru-cache";
8
+ //# sourceMappingURL=collections.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collections.js","sourceRoot":"","sources":["../src/collections.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,UAAU,EAAiB,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,QAAQ,EAAwB,MAAM,yBAAyB,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAwB,MAAM,yBAAyB,CAAC"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Assorted decorators.
3
+ * @module
4
+ */
5
+ /**
6
+ * Decorate a getter to cache its result.
7
+ *
8
+ * Useful for deferring initialisation of a property until first access.
9
+ * Instead of `myProperty = new Thing();`,
10
+ * use `@cache get myProperty() { return new Thing(); }`.
11
+ */
12
+ export declare function cache<C extends object, T>(getter: (this: C) => T, context: ClassGetterDecoratorContext<C, T>): (this: C) => T;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Tools for working with {@link Disposable}s and things that should have been
3
+ * {@link Disposable}.
4
+ *
5
+ * @module
6
+ */
7
+ import type { Constructor } from "type-fest";
8
+ import type { Unsubscribable } from "type-fest/globals";
9
+ /**
10
+ * Test whether something implements {@link Disposable}.
11
+ */
12
+ export declare function isDisposable(value: unknown): value is Disposable;
13
+ /**
14
+ * Type for something that can be turned into a {@link Disposable}.
15
+ *
16
+ * Includes things that already implement {@link Disposable}, objects with an
17
+ * `unsubscribe()` method (an {@link Unsubscribable}), and functions
18
+ * with no arguments or return values which are assumed to be unsubscribe
19
+ * functions, as popularised by React.
20
+ */
21
+ export type Disposifiable = (() => void) | Unsubscribable | Disposable;
22
+ /**
23
+ * Construct a new {@link Disposable} out of any {@link Disposifiable}.
24
+ *
25
+ * This constructs a new object which implements {@link Disposable}, and nothing
26
+ * else. The new object's dispose method will dispose of the original
27
+ * {@link Disposifiable}, and ensure that this happens only once, regardless of
28
+ * how many times the dispose method is called.
29
+ */
30
+ export declare function toDisposable(value: Disposifiable): Disposable;
31
+ /**
32
+ * Test whether something is {@link Disposifiable}.
33
+ *
34
+ * This is true if that something implements either of {@link Disposable} or
35
+ * {@link Unsubscribable}, or if it is a function.
36
+ */
37
+ export declare function isDisposifiable(value: unknown): value is Disposifiable;
38
+ /**
39
+ * Call {@link setTimeout} with the provided callback and return a
40
+ * {@link Disposable} which will cancel the timeout when disposed.
41
+ */
42
+ export declare function timeout(fn: () => void, timeout: number | Temporal.Duration): Disposable;
43
+ /**
44
+ * Call {@link setInterval} with the provided callback and return a
45
+ * {@link Disposable} which will cancel the interval when disposed.
46
+ */
47
+ export declare function interval(fn: () => void, interval: number | Temporal.Duration): Disposable;
48
+ export declare function idleCallback(callback: IdleRequestCallback, options?: IdleRequestOptions): Disposable;
49
+ /**
50
+ * An implementation of {@link AbortController} which also implements
51
+ * {@link Disposable}.
52
+ *
53
+ * Disposing the controller automatically triggers the abort signal.
54
+ */
55
+ export declare class DisposableAbortController implements AbortController, Disposable {
56
+ #private;
57
+ get signal(): AbortSignal;
58
+ abort(reason?: any): void;
59
+ [Symbol.dispose](): void;
60
+ }
61
+ /**
62
+ * Create an {@link AbortController} which also implements {@link Disposable}.
63
+ *
64
+ * Disposing the controller automatically triggers the abort signal.
65
+ *
66
+ * @returns A {@link DisposableAbortController}.
67
+ */
68
+ export declare function abortController(): DisposableAbortController;
69
+ export interface DisposableContext extends Disposable {
70
+ /**
71
+ * Disposes the resources currently held by this context.
72
+ */
73
+ dispose(): void;
74
+ /**
75
+ * Register a {@link Disposifiable} resource with this context, to be
76
+ * disposed along with it.
77
+ *
78
+ * @returns The {@link Disposable} that was registered with the context.
79
+ */
80
+ use(resource: null): null;
81
+ use(resource: undefined): undefined;
82
+ use(resource: Disposifiable): Disposable;
83
+ use(resource: Disposifiable | undefined): Disposable | undefined;
84
+ use(resource: Disposifiable | null | undefined): Disposable | null | undefined;
85
+ adopt<A>(value: A, onDispose: (value: A) => void): A;
86
+ }
87
+ /**
88
+ * A reentrant version of {@link DisposableStack}.
89
+ *
90
+ * This maintains a list of {@link Disposable}s, added with the
91
+ * {@link DisposableContext.use} method, which will all be disposed when you
92
+ * dispose of the {@link DisposableContext} itself.
93
+ *
94
+ * Where this differs from {@link DisposableStack} is that disposing it only
95
+ * resets it after disposing of its dependents, and you can reuse it as many
96
+ * times as you like. This is very handy for managing lifecycle resources, eg. a
97
+ * web component can allocate resources in its `connectedCallback` method and
98
+ * during its connected lifecycle phase which can all be disposed in
99
+ * `disconnectedCallback` with a single call to
100
+ * {@link DisposableContext.dispose}, and it's instantly ready to go again on
101
+ * reconnect.
102
+ *
103
+ * @class
104
+ */
105
+ export declare const DisposableContext: Constructor<DisposableContext>;
106
+ /**
107
+ * A class mixin which provides a {@link Disposable} implementation.
108
+ *
109
+ * The `use(resource)` method can be used to register {@link Disposifiable}
110
+ * resources which will be disposed when the object's dispose method is called.
111
+ */
112
+ export declare const AutoDisposable: <C extends Constructor<object>>(superclass: C) => {
113
+ new (...arguments_: any[]): {
114
+ __context?: DisposableContext;
115
+ use(resource: null): null;
116
+ use(resource: undefined): undefined;
117
+ use(resource: Disposifiable): Disposable;
118
+ use(resource: Disposifiable | undefined): Disposable | undefined;
119
+ use(resource: Disposifiable | null | undefined): Disposable | null | undefined;
120
+ [Symbol.dispose](): void;
121
+ };
122
+ } & C;
@@ -0,0 +1 @@
1
+ export {};
package/dist/fun.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The functional programmer's toolkit.
3
+ * @module
4
+ */
5
+ /**
6
+ * Create a function that always returns `value`.
7
+ *
8
+ * @example
9
+ * ```ts @import.meta.vitest
10
+ * const alwaysFive: () => number = always(5);
11
+ * expect(alwaysFive()).toEqual(5);
12
+ * ```
13
+ */
14
+ export declare function always<A>(value: A): () => A;
15
+ /**
16
+ * The identity function: it just returns its argument unchanged.
17
+ *
18
+ * @example
19
+ * ```ts @import.meta.vitest
20
+ * expect(id(1337)).toEqual(1337);
21
+ * expect(id("Hello Joe!")).toEqual("Hello Joe!");
22
+ * ```
23
+ */
24
+ export declare function id<A>(value: A): A;
25
+ /**
26
+ * A function which does nothing and returns `void`.
27
+ */
28
+ export declare function nop(): void;
29
+ /**
30
+ * A function which applies the `+` operator to its arguments.
31
+ *
32
+ * @example
33
+ * ```ts @import.meta.vitest
34
+ * expect(sum(2, 3)).toEqual(5);
35
+ * expect(sum("foo", "bar")).toEqual("foobar");
36
+ * ```
37
+ */
38
+ export declare function sum(a: number, b: number): number;
39
+ export declare function sum(a: bigint, b: bigint): bigint;
40
+ export declare function sum(a: string, b: string): string;
package/dist/fun.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The functional programmer's toolkit.
3
+ * @module
4
+ */
5
+ /**
6
+ * Create a function that always returns `value`.
7
+ *
8
+ * @example
9
+ * ```ts @import.meta.vitest
10
+ * const alwaysFive: () => number = always(5);
11
+ * expect(alwaysFive()).toEqual(5);
12
+ * ```
13
+ */
14
+ export function always(value) {
15
+ return () => value;
16
+ }
17
+ /**
18
+ * The identity function: it just returns its argument unchanged.
19
+ *
20
+ * @example
21
+ * ```ts @import.meta.vitest
22
+ * expect(id(1337)).toEqual(1337);
23
+ * expect(id("Hello Joe!")).toEqual("Hello Joe!");
24
+ * ```
25
+ */
26
+ export function id(value) {
27
+ return value;
28
+ }
29
+ /**
30
+ * A function which does nothing and returns `void`.
31
+ */
32
+ export function nop() {
33
+ // nop
34
+ }
35
+ export function sum(a, b) {
36
+ // @ts-ignore
37
+ // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
38
+ return a + b;
39
+ }
40
+ //# sourceMappingURL=fun.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fun.js","sourceRoot":"","sources":["../src/fun.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;;;;;GAQG;AACH,MAAM,UAAU,MAAM,CAAI,KAAQ;IAC9B,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC;AACvB,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,EAAE,CAAI,KAAQ;IAC1B,OAAO,KAAK,CAAC;AACjB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,GAAG;IACf,MAAM;AACV,CAAC;AAcD,MAAM,UAAU,GAAG,CAAqC,CAAI,EAAE,CAAI;IAC9D,aAAa;IACb,qEAAqE;IACrE,OAAO,CAAC,GAAG,CAAC,CAAC;AACjB,CAAC"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Sorting and ordering.
3
+ * @module
4
+ */
5
+ import { type Option } from "@bodil/opt";
6
+ export declare enum Cmp {
7
+ /** Less than. */
8
+ LT = -1,
9
+ /** Equal to. */
10
+ EQ = 0,
11
+ /** Greater than. */
12
+ GT = 1
13
+ }
14
+ /**
15
+ * An order function is a function which is used to compare two items, returning
16
+ * a {@link Cmp} to describe the first item in relation to the second, eg.
17
+ * {@link Cmp.GT} says the first item is greater than the second item.
18
+ */
19
+ export type OrderFn<A> = (left: A, right: A) => Cmp;
20
+ /**
21
+ * The set of types which can be compared using the `<` and `>` operators.
22
+ */
23
+ export type OperatorComparable = number | string | bigint | Date;
24
+ /**
25
+ * An order function which sorts {@link OperatorComparable} items in ascending
26
+ * order.
27
+ */
28
+ export declare function ascending<A extends OperatorComparable>(left: A, right: A): Cmp;
29
+ /**
30
+ * An order function which sorts {@link OperatorComparable} items in descending
31
+ * order.
32
+ */
33
+ export declare function descending<A extends OperatorComparable>(left: A, right: A): Cmp;
34
+ /**
35
+ * Take an order function and invert its order.
36
+ */
37
+ export declare function reverse<T>(fn: OrderFn<T>): OrderFn<T>;
38
+ /**
39
+ * Given a value, a sorted array and a comparison function by which the array
40
+ * has been sorted, find the lowest index at which the value could be inserted
41
+ * while maintaining sort order.
42
+ */
43
+ export declare function bisectLow<A>(cmp: OrderFn<A>, array: Array<A>, key: A): number;
44
+ /**
45
+ * Given a value, a sorted array and a comparison function by which the array
46
+ * has been sorted, find the highest index at which the value could be inserted
47
+ * while maintaining sort order.
48
+ */
49
+ export declare function bisectHigh<A>(cmp: OrderFn<A>, array: Array<A>, key: A): number;
50
+ /**
51
+ * Given a value, a sorted array and a comparison function by which the array
52
+ * has been sorted, find the index of the specific value if it exists in the
53
+ * array.
54
+ */
55
+ export declare function find<A>(cmp: OrderFn<A>, array: Array<A>, key: A): Option<number>;
@@ -0,0 +1 @@
1
+ import "@bodil/opt-vitest";
package/dist/time.d.ts ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Utilities for working with {@link Temporal}.
3
+ * @module
4
+ */
5
+ /**
6
+ * Test if the given {@link Temporal.Instant} comes before a certain moment
7
+ * in time.
8
+ *
9
+ * If `other` is unspecified, compare with the current time.
10
+ *
11
+ * If `other` is a {@link Temporal.Duration}, compare with that duration
12
+ * subtracted from the current time.
13
+ *
14
+ * If `other` is a {@link Temporal.Instant}, compare with that instant.
15
+ *
16
+ * @example
17
+ * time.isBefore(instant) // is `instant` in the past?
18
+ * time.isBefore(instant, otherInstant) // is `instant` before `otherInstant`?
19
+ * time.isBefore(instant, duration) // is `instant` more than `duration` ago?
20
+ */
21
+ export declare function isBefore(instant: Temporal.Instant, other?: Temporal.Instant | Temporal.Duration): boolean;
22
+ /**
23
+ * Test if the given {@link Temporal.Instant} comes after a certain moment in
24
+ * time.
25
+ *
26
+ * If `other` is unspecified, compare with the current time.
27
+ *
28
+ * If `other` is a {@link Temporal.Duration}, compare with that duration added
29
+ * to the current time.
30
+ *
31
+ * If `other` is a {@link Temporal.Instant}, compare with that instant.
32
+ *
33
+ * @example
34
+ * time.isAfter(instant) // is `instant` in the future?
35
+ * time.isAfter(instant, otherInstant) // is `instant` after `otherInstant`?
36
+ * time.isAfter(instant, duration) // is `instant` more than `duration` into the future?
37
+ */
38
+ export declare function isAfter(instant: Temporal.Instant, other?: Temporal.Instant | Temporal.Duration): boolean;
39
+ /**
40
+ * Find the shortest duration or earliest time given a series of
41
+ * {@link Temporal.Duration}s or {@link Temporal.Instant}s.
42
+ */
43
+ export declare function min<T extends Temporal.Duration | Temporal.Instant>(...rest: Array<T>): T;
44
+ /**
45
+ * Find the longest duration or latest time given a series of
46
+ * {@link Temporal.Duration}s or {@link Temporal.Instant}s.
47
+ */
48
+ export declare function max<T extends Temporal.Duration | Temporal.Instant>(...rest: Array<T>): T;
49
+ /**
50
+ * The current time as a {@link Temporal.Instant}.
51
+ *
52
+ * A shorthand for `Temporal.Now.instant()`.
53
+ */
54
+ export declare function now(): Temporal.Instant;
55
+ /**
56
+ * The current time as a {@link Temporal.ZonedDateTime}.
57
+ *
58
+ * A shorthand for `Temporal.Now.zonedDateTimeISO()`.
59
+ */
60
+ export declare function nowZ(): Temporal.ZonedDateTime;
61
+ /**
62
+ * Construct a duration of the given number of days.
63
+ */
64
+ export declare function days(days: number): Temporal.Duration;
65
+ /**
66
+ * Construct a duration of the given number of hours.
67
+ */
68
+ export declare function hours(hours: number): Temporal.Duration;
69
+ /**
70
+ * Construct a duration of the given number of minutes.
71
+ */
72
+ export declare function minutes(minutes: number): Temporal.Duration;
73
+ /**
74
+ * Construct a duration of the given number of seconds.
75
+ */
76
+ export declare function seconds(seconds: number): Temporal.Duration;
77
+ /**
78
+ * Construct a duration of the given number of milliseconds.
79
+ */
80
+ export declare function millis(milliseconds: number): Temporal.Duration;
@@ -0,0 +1 @@
1
+ import "temporal-polyfill/global";
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Utility types.
3
+ * @module
4
+ */
5
+ /**
6
+ * Constructs a type by excluding `undefined` from `T`.
7
+ *
8
+ * This is like {@link NonNullable} but it only removes `undefined`, not `null`.
9
+ */
10
+ export type Present<T> = T extends undefined ? never : T;
11
+ /**
12
+ * Interface for classes which implement equality checking.
13
+ */
14
+ export interface Equals {
15
+ /** Tests whether a given value is equal to this value. */
16
+ equals(other: unknown): boolean;
17
+ }
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Utility types.
3
+ * @module
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bodil/core",
3
- "version": "0.5.8",
3
+ "version": "0.5.9",
4
4
  "description": "My TypeScript standard library",
5
5
  "repository": {
6
6
  "type": "git",
@@ -140,6 +140,6 @@
140
140
  "check": "run-p check:tsc check:eslint",
141
141
  "doc": "typedoc",
142
142
  "doc:readthedocs": "typedoc --out $READTHEDOCS_OUTPUT/html",
143
- "prepublish": "tsc"
143
+ "prepublish": "rm -rf dist && tsc"
144
144
  }
145
145
  }