Skip to main content

๐Ÿ› ๏ธ Utilities

Overviewโ€‹

@digital-alchemy/core exposes a few utilities out outside the main TServiceParams wrapper. These are intended for convenience, and

sleepโ€‹

A setTimeout that can be awaited, with a few tricks up it's sleeve. Basic usage:

async function myLogic() {
// some logic
await sleep(1000);
// more logic
}

You may provide ms timeout, or Date to wait until a target time. The sleep itself may be interacted with by other logic, providing a kill method that that allows different outcomes:

  • stop: stop the sleep and discard promise (garbage collect)
  • continue: stop the sleep and return immediately
entity.onEvent(() => {
if (!timer) {
return;
}
timer.kill("stop");
timer = undefined;

})
let timer: SleepReturn;
async function myLogic() {
// some logic
timer?.kill("stop"); // stop previous
timer = sleep(1000 * 60 * 60 * 24); // create new
await timer;
logger.thing("timer was not cancelled after 24h");
timer = undefined;
}

throttle & debounceโ€‹

The throttle & debounce are similar methods that can be used to help logic not run too often.

  • throttle: allow the first call, then block for a duration before allowing next
  • debounce: wait for duration before allowing, additional calls inside that window remove previous
myEntity.onEvent(() => {
await debounce("my_special_debounce", 250);
logger.info("debounced!");
})

isโ€‹

The is object is a grab bag of canned type assertions and quick transformations. It aims to provide a common grammar for the various assertions made across the framework that is type safe.

MethodLibraryNotes
is.arraycoreWrapper for Array.isArray
is.booleancoretypeof wrapper
is.contextcoreassertion tool for internals
is.datecoretype check
is.emptycorereturns true for things that have content (non-empty strings, objects with keys, etc)
is.equalcoreDeep equality test
is.evencore
is.functioncoretypeof wrapper
is.numbercoretypeof wrapper
is.objectcoretypeof wrapper, false for arrays and null
is.randomcoreselects a random item out of provided array
is.stringcoretypeof wrapper
is.symbolcoretypeof wrapper
is.undefinedcoretypeof wrapper
is.uniquecoretakes array of things, removes duplicates using Set
is.domainhasscheck if an entity belongs to a domain