Added some doc strings & sleepUntil function
All checks were successful
Build / Build NPM Project (push) Successful in 50s
Build / Tag Version (push) Successful in 7s

This commit is contained in:
Zakary Timson 2024-08-27 11:41:22 -04:00
parent 57446ef09a
commit 20f36cc573
3 changed files with 101 additions and 38 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.15.1", "version": "0.15.2",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",

View File

@ -1,57 +1,108 @@
/**
* An array which functions as a set. It guarantees unique elements
* and provides set functions for comparisons
*/
export class ASet<T> extends Array { export class ASet<T> extends Array {
/** Number of elements in set */
get size() { get size() {
return this.length; return this.length;
} }
/**
* Array to create set from, duplicate values will be removed
* @param {T[]} elements Elements which will be added to set
*/
constructor(elements: T[] = []) { constructor(elements: T[] = []) {
super(); super();
if(!!elements?.['forEach']) if(!!elements?.['forEach'])
elements.forEach(el => this.add(el)); elements.forEach(el => this.add(el));
} }
/**
* Add single element to set if unique
* @param {T} el Element to add
*/
add(el: T) { add(el: T) {
if(!this.has(el)) this.push(el); if(!this.has(el)) this.push(el);
} }
/**
* Delete element from set
* @param {T} el Element that will be deleted
*/
delete(el: T) { delete(el: T) {
const index = this.indexOf(el); const index = this.indexOf(el);
if(index != -1) this.slice(index, 1); if(index != -1) this.slice(index, 1);
} }
/**
* Create list of elements this set has which the comparison set does not
* @param {ASet<T>} set Set to compare against
* @return {ASet<T>} Different elements
*/
difference(set: ASet<T>) { difference(set: ASet<T>) {
return new ASet<T>(this.reduce((acc, el) => { return new ASet<T>(this.filter(el => !set.has(el)));
if(!set.has(el)) acc.push(el);
return acc;
}, []));
} }
/**
* Check if set includes element
* @param {T} el Element to look for
* @return {boolean} True if element was found, false otherwise
*/
has(el: T) { has(el: T) {
return this.indexOf(el) != -1; return this.indexOf(el) != -1;
} }
/**
* Create list of elements this set has in common with the comparison set
* @param {ASet<T>} set Set to compare against
* @return {boolean} Set of common elements
*/
intersection(set: ASet<T>) { intersection(set: ASet<T>) {
return new ASet<T>(this.reduce((acc, el) => { return new ASet<T>(this.filter(el => set.has(el)));
if(set.has(el)) acc.push(el);
return acc;
}, []));
} }
/**
* Check if this set has no elements in common with the comparison set
* @param {ASet<T>} set Set to compare against
* @return {boolean} True if nothing in common, false otherwise
*/
isDisjointFrom(set: ASet<T>) { isDisjointFrom(set: ASet<T>) {
return this.intersection(set).size == 0; return this.intersection(set).size == 0;
} }
/**
* Check if all elements in this set are included in the comparison set
* @param {ASet<T>} set Set to compare against
* @return {boolean} True if all elements are included, false otherwise
*/
isSubsetOf(set: ASet<T>) { isSubsetOf(set: ASet<T>) {
return this.findIndex(el => !set.has(el)) == -1; return this.findIndex(el => !set.has(el)) == -1;
} }
/**
* Check if all elements from comparison set are included in this set
* @param {ASet<T>} set Set to compare against
* @return {boolean} True if all elements are included, false otherwise
*/
isSuperset(set: ASet<T>) { isSuperset(set: ASet<T>) {
return set.findIndex(el => !this.has(el)) == -1; return set.findIndex(el => !this.has(el)) == -1;
} }
/**
* Create list of elements that are only in one set but not both (XOR)
* @param {ASet<T>} set Set to compare against
* @return {ASet<T>} New set of unique elements
*/
symmetricDifference(set: ASet<T>) { symmetricDifference(set: ASet<T>) {
return new ASet([...this.difference(set), ...set.difference(this)]); return new ASet([...this.difference(set), ...set.difference(this)]);
} }
/**
* Create joined list of elements included in this & the comparison set
* @param {ASet<T>} set Set join
* @return {ASet<T>} New set of both previous sets combined
*/
union(set: ASet<T> | Array<T>) { union(set: ASet<T> | Array<T>) {
return new ASet([...this, ...set]); return new ASet([...this, ...set]);
} }

View File

@ -1,32 +1,3 @@
/**
* Calculate the number of milliseconds until date/time
*
* @param {Date | number} date - Target
* @returns {number} - Number of milliseconds until target
*/
export function timeUntil(date: Date | number): number {
return (date instanceof Date ? date.getTime() : date) - (new Date()).getTime();
}
/**
* Use in conjunction with `await` to pause an async script
*
* @example
* ```ts
* async () => {
* ...
* await sleep(1000) // Pause for 1 second
* ...
* }
* ```
*
* @param {number} ms - Time to pause for in milliseconds
* @returns {Promise<unknown>} - Resolves promise when it's time to resume
*/
export function sleep(ms: number) {
return new Promise(res => setTimeout(res, ms));
}
export function formatDate(date: Date | number | string) { export function formatDate(date: Date | number | string) {
const d = date instanceof Date ? date : new Date(date); const d = date instanceof Date ? date : new Date(date);
return new Intl.DateTimeFormat("en-us", { return new Intl.DateTimeFormat("en-us", {
@ -38,3 +9,44 @@ export function formatDate(date: Date | number | string) {
hour12: true hour12: true
}).format(d); }).format(d);
} }
/**
* Use in conjunction with `await` to pause an async script
*
* @example
* ```js
* await sleep(1000) // Pause for 1 second
* ```
* @param {number} ms - Time to pause for in milliseconds
* @returns {Promise<unknown>} - Resolves promise when it's time to resume
*/
export function sleep(ms: number): Promise<void> {
return new Promise(res => setTimeout(res, ms));
}
/**
* Sleep while function returns true
*
* @example
* ```js
* let loading = true;
* setTimeout(() => wait = false, 1000);
* await sleepUntil(() => loading); // Won't continue until loading flag is false
* ```
* @param {() => boolean} fn Return true to continue
* @param {number} checkInterval Run function ever x milliseconds
* @return {Promise<void>} Callback when sleep is over
*/
export async function sleepUntil(fn : () => boolean, checkInterval=100): Promise<void> {
while(fn()) await sleep(checkInterval);
}
/**
* Calculate the number of milliseconds until date/time
*
* @param {Date | number} date - Target
* @returns {number} - Number of milliseconds until target
*/
export function timeUntil(date: Date | number): number {
return (date instanceof Date ? date.getTime() : date) - (new Date()).getTime();
}