@jkhong/devutils
v1.7.1
Published
Provides some syntactic sugar and shortcuts to bullet proof your devs
Readme
@jkhong/devutils
Provides syntactic sugar and shortcuts to bullet-proof your TypeScript/JavaScript code.
Contents
- Install
- DevUtils —
isSet·isNotSet·isAllSet·isOneNotSet·isEmpty·getFieldValue·getChildFieldValue·makeSingleton·debounce·getError - StringUtils —
isBlank·capitalize·uncapitalize·replaceTrailing·replaceLeading - ArrayUtils —
isEmpty·getField - DateUtils —
addDays·addMinutes·addSeconds - FunctionUtils —
isAsync - InMemory — TTL-based in-memory cache
- TestUtils — async test helpers
Install
npm install @jkhong/devutilsDevUtils
isSet(value)
Returns true if the value is not null, not undefined, and not the string 'undefined'.
import { DevUtils } from '@jkhong/devutils';
DevUtils.isSet(null); // false
DevUtils.isSet(undefined); // false
DevUtils.isSet('undefined'); // false
DevUtils.isSet(0); // true
DevUtils.isSet(''); // true
DevUtils.isSet(false); // trueisNotSet(value)
Inverse of isSet.
isAllSet(memberNames, data) / isOneNotSet(memberNames, data)
Check if all (or at least one) named fields of an object are set.
DevUtils.isAllSet(['id', 'name'], { id: 1, name: 'foo' }); // true
DevUtils.isOneNotSet(['id', 'name'], { id: 1 }); // trueisEmpty(value)
Returns true for null, undefined, empty/blank strings, empty arrays, and empty objects.
DevUtils.isEmpty(null); // true
DevUtils.isEmpty(' '); // true
DevUtils.isEmpty([]); // true
DevUtils.isEmpty({}); // true
DevUtils.isEmpty([1]); // false
DevUtils.isEmpty({ a: 1 }); // falsegetFieldValue(struct, fieldname, default)
Returns the field value if set, otherwise the default.
DevUtils.getFieldValue({ age: 30 }, 'age', 0); // 30
DevUtils.getFieldValue({}, 'age', 0); // 0
DevUtils.getFieldValue(null, 'age', 0); // 0getChildFieldValue(struct, fieldnames, default)
Traverses nested objects safely, returning the default if any level is missing.
const obj = { a: { b: { c: 'deep' } } };
DevUtils.getChildFieldValue(obj, ['a', 'b', 'c'], 'default'); // 'deep'
DevUtils.getChildFieldValue(obj, ['a', 'x', 'c'], 'default'); // 'default'makeSingleton(asyncFactory)
Wraps an async factory so it is called only once. Subsequent calls return the cached instance.
const getDb = DevUtils.makeSingleton(() => connectToDatabase());
await getDb(); // connects
await getDb(); // returns cached connectiondebounce(fn, waitMs)
Returns a debounced version of fn that fires only after waitMs ms of inactivity.
const save = DevUtils.debounce(() => api.save(), 300);
save(); save(); save(); // only the last call fires after 300msgetError(e)
Normalizes any thrown value to an Error instance. Useful in catch (e: unknown) blocks.
try { ... } catch (e: unknown) {
const err = DevUtils.getError(e); // always an Error
}StringUtils
import { StringUtils } from '@jkhong/devutils';| Method | Description |
|---|---|
| isBlank(str) | true if string is null, undefined, or contains only whitespace |
| capitalize(word) | Uppercases the first character |
| uncapitalize(word) | Lowercases the first character |
| replaceTrailing(value, char, replacement) | Replaces trailing occurrences of char |
| replaceLeading(value, char, replacement) | Replaces leading occurrences of char |
StringUtils.capitalize('hello'); // 'Hello'
StringUtils.uncapitalize('World'); // 'world'
StringUtils.replaceTrailing('foo///', '/', ''); // 'foo'
StringUtils.replaceLeading('///foo', '/', ''); // 'foo'ArrayUtils
import { ArrayUtils } from '@jkhong/devutils';| Method | Description |
|---|---|
| isEmpty(array) | true if array is null, undefined, or has no elements |
| getField(array, index, fieldname, default) | Safely reads a field from an element at a given index |
ArrayUtils.isEmpty([]); // true
ArrayUtils.getField([{ id: 1 }], 0, 'id', null); // 1
ArrayUtils.getField([], 0, 'id', null); // nullDateUtils
import { DateUtils } from '@jkhong/devutils';| Method | Description |
|---|---|
| addDays(date, n) | Returns a new Date with n days added |
| addMinutes(date, n) | Returns a new Date with n minutes added |
| addSeconds(date, n) | Returns a new Date with n seconds added |
Accepts negative values to subtract. The original date is never mutated.
DateUtils.addDays(new Date(), 7); // one week from now
DateUtils.addSeconds(new Date(), -30); // 30 seconds agoFunctionUtils
import { FunctionUtils } from '@jkhong/devutils';| Method | Description |
|---|---|
| isAsync(fn) | true if the function is async |
FunctionUtils.isAsync(async () => {}); // true
FunctionUtils.isAsync(() => {}); // falseInMemory (cache)
A TTL-based in-memory cache with per-entry TTL support and automatic background cleanup.
import { InMemory } from '@jkhong/devutils';Constructor options
| Option | Default | Description |
|---|---|---|
| ttlInSec | 3600 (1h) | Default TTL for entries |
| autoTtlCleanIntervalInSec | 3600 (1h) | How often expired entries are swept |
| autoWipeAllIntervalInSec | disabled | How often the entire cache is cleared (opt-in) |
Methods
add({ id, d, ttlInSec? })
Adds or overwrites an entry. ttlInSec overrides the global default for this entry.
const cache = new InMemory<User>({ ttlInSec: 300 });
await cache.add({ id: 'u1', d: user });
await cache.add({ id: 'u2', d: user, ttlInSec: 60 }); // custom TTLfetch(id)
Returns the cached value or undefined if missing or expired.
const user = await cache.fetch('u1'); // User | undefinedfetchMultiple(ids)
Splits a list of ids into cached hits and ids that still need to be fetched from the source.
const { cachedData, idsToRequest } = await cache.fetchMultiple(['u1', 'u2', 'u3']);
// cachedData → [{ id: 'u1', data: User }, ...]
// idsToRequest → ['u3']
const fresh = await api.getUsers(idsToRequest);remove(id)
Removes a single entry immediately.
await cache.remove('u1');forceTtlClean()
Triggers an immediate sweep to remove all expired entries.
forceWipeAll()
Clears all entries regardless of TTL.
destroy()
Stops background intervals and clears the cache. Call this when the cache instance is no longer needed to prevent timer leaks.
await cache.destroy();TestUtils
Helpers for structuring async tests with setup / run / assert phases.
import { TestUtils } from '@jkhong/devutils';testExpectedSuccess({ setPreconditions, run, checkPostconditions })
For testing a happy path. Returns { success: true } or { success: false, error }.
const result = await TestUtils.testExpectedSuccess({
setPreconditions: async () => buildInput(),
run: async (input) => myService.process(input),
checkPostconditions: async (output) => {
expect(output.status).toBe('ok');
},
});
expect(result.success).toBe(true);testExpectedError({ setPreconditions, run, checkError, checkPostconditions })
For testing flows that return an error value (no exception thrown).
testExpectedException({ setPreconditions, run, checkError, checkPostconditions })
For testing flows that are expected to throw.
