@yuuza/utils
v1.0.3
Published
Events in JS/TS with easy typing/autocompletion.
Downloads
2
Readme
@yuuza/utils
Classes
Callbacks
Events in JS/TS with easy typing/autocompletion.
Example:
class MusicPlayer {
onPlay = new Callbacks<() => void>();
// ...
play() {
// ...
// Call/invoke the callbacks:
this.onPlay.invoke();
}
}
const player = new MusicPlayer();
// ...
player.onPlay.add(() => {
console.info("player play");
});
Ref
Ref with onChanged
callbacks.
Example:
class MusicPlayer {
refState = new Ref<"stopped" | "playing" | "paused">("stopped");
// ...
play() {
// ...
this.refState.value = "playing";
}
}
const player = new MusicPlayer();
// ...
player.refState.onChanged.add(() => {
console.info("player current state:", player.refState.value);
});
Semaphore
Example:
// Limit the concurrency of downloads
const downloadLimit = new Semaphore({ maxCount: 5 });
async function download() {
// Will block/await here if >= 5 downloads currently running,
await downloadLimit.enter();
try {
await actuallyDownload();
} finally {
downloadLimit.exit();
}
}
Or shorter version with run()
:
const downloadLimit = new Semaphore({ maxCount: 5 });
function download() {
return downloadLimit.run(async () => {
await actuallyDownload();
});
}
Lazy
CancelToken
AutoResetEvent
EventRegistrations
Functions
(TBD)
strPadLeft
function strPadLeft(str: string, len: number, ch?: string): string;
formatDuration
function formatDuration(sec: number | any): string;
formatFileSize
function formatFileSize(size: number | any): string;
formatDateTime
function formatDateTime(date: Date): string;
numLimit
function numLimit(num: number, min: number, max: number): number;
createName
function createName(
nameFunc: (num: number) => string,
existsFunc: (str: string) => boolean
): string;
base64EncodeUtf8
function base64EncodeUtf8(str: any): string;
sleepAsync
function sleepAsync(time: number): Promise<void>;
arrayRemove
function arrayRemove<T>(array: T[], val: T): void;
arrayInsert
function arrayInsert<T>(array: T[], val: T, pos?: number): void;
arrayMap
function arrayMap<T, TRet>(
arr: Iterable<T>,
func: (item: T, idx: number) => TRet
): TRet[];
arrayForeach
function arrayForeach<T>(
arr: Iterable<T>,
func: (item: T, idx: number) => void
): void;
foreachFlaten
function foreachFlaten<T>(arr: T[], func: Action<T>): void;
arrayFind
function arrayFind<T>(
arr: Iterable<T>,
func: (item: T, idx: number) => any
): T | null;
arraySum
function arraySum<T>(
arr: Iterable<T>,
func: (item: T) => number | null | undefined
): number;
objectApply
function objectApply<T>(
obj: Partial<T>,
kv?: Partial<T>,
keys?: Array<keyof T>
): Partial<T>;
objectInit
function objectInit<T>(obj: T, kv?: ObjectInit<T>, keys?: Array<keyof T>): T;
mod
function mod(a: number, b: number): number;
readBlobAsDataUrl
function readBlobAsDataUrl(blob: Blob): Promise<string>;