@yungezeit/utils
v0.0.7
Published
Personal re-usable ES/TS utilities
Downloads
820
Maintainers
Readme
@yungezeit/utils
(Not so) Personal re-usable ES/TS utilities.
Install
# Using npm
npm i -D @yungezeit/utils
# Using Yarn
yarn add -D @yungezeit/utils
# Using pnpm
pnpm add -D @yungezeit/utils
# Using bun
bun add -D @yungezeit/utilsFeatures
JSON stringify/parse with Map and Set support
import { JSONX } from '@yungezeit/utils';
const json = JSONX.stringify({
someMap: new Map([
['key1', 'value-of-key1'],
['key2', 'value-of-key2'],
]),
someSet: new Set(['item1', 'item2']),
});
const parsed = JSONX.parse(json);
const someMapItem = parsed.someMap.get('key2'); // "value-of-key2"
const someSetItem = parsed.someSet.has('item2'); // trueMap with benefits
Adds an optional second argument to Map's get method which can be used to provide a default value if the key does not exist. This default value is not only returned but also set in the map. Providing a default value also marks the return type as non-nullable.
import { MapX } from '@yungezeit/utils';
type MyMap = MapX<string, number>;
const myMap: MyMap = new MapX([]);
myMap.get('key1', 42); // 42
myMap.has('key1'); // trueNotes:
- This does not change the original Map prototype.
- A map value can exist and still be
undefined, but the default value logic relies on whether the second argument was defined or not. This means you can't useundefinedas a default value.
Measure async work
Measure elapsed time for async functions and optionally capture thrown errors (errors are not caught by default).
import { measure } from '@yungezeit/utils';
const result = await measure(async () => { … }, { catchErrors: true });
if ('output' in result) {
console.info(`Completed in ${result.formattedTime}: `, result.output);
}
if ('error' in result) {
console.error(`Failed after ${result.formattedTime}:`, result.error);
}Notes:
- By default,
measurerethrows errors. SetcatchErrors: trueto return an object with anerrorpayload instead. This might be useful when you still want to collect the elapsed time for failed operations.
