mirror of
https://github.com/discordjs/discord.js.git
synced 2026-03-12 17:43:30 +01:00
feat: add @discordjs/util (#8591)
* feat: add @discordjs/util * fix: builders test * refactor: make rest use lazy for ESM import * chore: make requested changes * Apply suggestions from code review Co-authored-by: Parbez <imranbarbhuiya.fsd@gmail.com> Co-authored-by: A. Román <kyradiscord@gmail.com> * chore: make requested changes and add tests * chore: regen lockfile * test: add type tests * chore: push missing files * chore: make requested changes * chore: update CI stuff * chore: fix lockfile * chore: make requested changes Co-authored-by: Parbez <imranbarbhuiya.fsd@gmail.com> Co-authored-by: A. Román <kyradiscord@gmail.com> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
2
packages/util/src/functions/index.ts
Normal file
2
packages/util/src/functions/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './lazy.js';
|
||||
export * from './range.js';
|
||||
18
packages/util/src/functions/lazy.ts
Normal file
18
packages/util/src/functions/lazy.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Lazy is a wrapper around a value that is computed lazily. It is useful for
|
||||
* cases where the value is expensive to compute and the computation may not
|
||||
* be needed at all.
|
||||
*
|
||||
* @param cb - The callback to lazily evaluate
|
||||
* @typeParam T - The type of the value
|
||||
* @example
|
||||
* ```ts
|
||||
* const value = lazy(() => computeExpensiveValue());
|
||||
* ```
|
||||
*/
|
||||
// eslint-disable-next-line promise/prefer-await-to-callbacks
|
||||
export function lazy<T>(cb: () => T): () => T {
|
||||
let defaultValue: T;
|
||||
// eslint-disable-next-line promise/prefer-await-to-callbacks
|
||||
return () => (defaultValue ??= cb());
|
||||
}
|
||||
20
packages/util/src/functions/range.ts
Normal file
20
packages/util/src/functions/range.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Yields the numbers in the given range as an array
|
||||
*
|
||||
* @param start - The start of the range
|
||||
* @param end - The end of the range (inclusive)
|
||||
* @param step - The amount to increment between each number
|
||||
* @example
|
||||
* Basic range
|
||||
* ```ts
|
||||
* range(3, 5); // [3, 4, 5]
|
||||
* ```
|
||||
* @example
|
||||
* Range with a step
|
||||
* ```ts
|
||||
* range(3, 10, 2); // [3, 5, 7, 9]
|
||||
* ```
|
||||
*/
|
||||
export function range(start: number, end: number, step = 1): number[] {
|
||||
return Array.from({ length: (end - start) / step + 1 }, (_, index) => start + index * step);
|
||||
}
|
||||
Reference in New Issue
Block a user