Utilities
@nscode/utils contains small helpers used inside the component library. They are also exported from @nscode/handy-ui, so your code can use them directly:
import { debounce, isEmpty, addClass } from '@nscode/handy-ui'
// or
import { debounce, isEmpty, addClass } from '@nscode/utils'
Type Checks
| Function | Description |
|---|---|
isString(val), isNumber(val), isBoolean(val), isFunction(val) | Check primitive types |
isThenable(val) | Whether an object or function has a callable then; supports Promises and custom thenables, and does not call then |
isArray(val) | Same as Array.isArray |
isObject(val) | Not null and typeof is object (arrays included) |
isEmpty(val) | true for null, undefined, empty strings, empty arrays and plain objects without properties; Map and Set are checked by size; 0, false, Date and other values return false |
Functions and Strings
| Function | Description |
|---|---|
debounce(fn, delay) | Debounce: when called repeatedly, runs once delay ms after the last call |
throttle(fn, delay) | Throttle: the first call runs immediately; the last call within an interval runs when it ends |
noop() | Empty function |
identity(val) | Returns its argument |
capitalize(str) | Uppercase the first letter: 'button' → 'Button' |
camelize(str) | Kebab-case to camelCase: 'date-picker' → 'datePicker' |
kebabCase(str) | camelCase to kebab-case: 'datePicker' → 'date-picker' |
import { debounce } from '@nscode/handy-ui'
const search = debounce((keyword: string) => {
// Sends the request only after typing stops for 300 ms
}, 300)
Functions returned by debounce and throttle have a cancel() method; call it when the component unmounts to drop the pending call. When called as an object method, this is passed to the original function.
DOM
| Function | Description |
|---|---|
isClient | Constant: whether running in a browser |
inBrowser() | Same as above, as a function |
isDocumentVisible() | Whether the page is visible (not in a background tab) |
isWindow(val) | Whether the value is the window object |
addEventListener(el, event, handler, options?), removeEventListener(...) | Typed event binding; event names depend on the target (beforeunload on window, visibilitychange on document) |
getComputedStyle(el) | Get the computed style of an element |
getScrollTop(el), setScrollTop(el, value) | Read and write the scroll position; el can be an element or window |
getOffset(el) | top and left of an element relative to the document |
addClass(el, ...classes), removeClass(el, ...classes), hasClass(el, className), toggleClass(el, className, force?) | Class name helpers |
Types
import type { ComponentSize, ComponentType, MaybeArray, Nullable } from '@nscode/handy-ui'
type ComponentSize = 'large' | 'default' | 'small'
type ComponentType = 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'help' | 'default'
type MaybeArray<T> = T | T[]
type MaybeFunction<T> = T | (() => T)
type Nullable<T> = T | null
type Optional<T> = T | undefined
Collection field mapping
CollectionFieldNames<T> is a shared mapping type available from @nscode/handy-ui and @nscode/utils. Its optional value, label, children, disabled and isLeaf fields accept a field name or (item: T) => unknown. Individual components select the fields appropriate to their data structure.
import type { CollectionFieldNames } from '@nscode/handy-ui'
interface City {
id: number
name: string
inactive?: boolean
children?: City[]
}
const fields: CollectionFieldNames<City> = {
value: 'id',
label: (city) => city.name,
children: 'children',
disabled: (city) => Boolean(city.inactive),
isLeaf: (city) => !city.children?.length
}
Object paths and dates
These helpers are available from both @nscode/utils and @nscode/handy-ui. Date functions follow the same rules used by the date picker.
getPropByPath
getPropByPath(obj: unknown, path: string) => unknown
Read a property by dotted or bracket path. Missing paths return undefined; an empty path returns the original object.
import { getPropByPath } from '@nscode/utils'
const model = { users: [{ name: 'Alex' }] }
getPropByPath(model, 'users[0].name') // 'Alex'
getPropByPath(model, 'users.0.name') // 'Alex'
setPropByPath
setPropByPath(obj: unknown, path: string, value: unknown) => void
Set the final property of an existing path without creating missing intermediate objects. An empty path leaves the object unchanged.
import { setPropByPath } from '@nscode/utils'
const model = { users: [{ name: 'Alex' }] }
setPropByPath(model, 'users.0.name', 'Sam')
// model.users[0].name === 'Sam'
cloneValue
cloneValue<T>(value: T) => T
Recursively clone arrays, plain objects and Date values, unwrapping existing Vue proxies. Blob, File and class instances retain their references. Circular references are unsupported.
import { cloneValue } from '@nscode/utils'
const original = { rows: [{ qty: 2 }], date: new Date(2026, 10, 19) }
const copy = cloneValue(original)
copy.rows[0].qty = 3
// original.rows[0].qty === 2
formatDate
formatDate(date: Date, format: string) => string
Format local date/time fields using YYYY/YY, MM/M, DD/D, HH/H, mm/m and ss/s. Z emits the local offset at that instant as ±HH:mm; ZZ emits ±HHmm. A UTC environment emits +00:00 / +0000. Date stores an instant without retaining the input offset: the same UTC instant displays local fields with +08:00 in a UTC+08:00 environment. Bracketed text is literal, including [Z] and [ZZ].
A complete x format returns a millisecond timestamp string; X returns a second timestamp string rounded down. The return type remains string; only DatePicker and DatePickerPanel convert these formats into numeric model values.
import { formatDate } from '@nscode/utils'
formatDate(new Date(2026, 10, 19, 9, 5, 3), 'YYYY-MM-DD HH:mm:ss') // '2026-11-19 09:05:03'
formatDate(new Date(1500), 'x') // '1500'
formatDate(new Date(-1), 'X') // '-1', rounded down to seconds
// The next two examples assume UTC+08:00; other time zones use their local fields and offsets.
formatDate(new Date('2024-01-01T00:15:00Z'), 'YYYY-MM-DDTHH:mm:ssZ') // '2024-01-01T08:15:00+08:00'
formatDate(new Date('2024-01-01T00:15:00Z'), 'YYYY-MM-DDTHH:mm:ssZZ') // '2024-01-01T08:15:00+0800'
formatDate(new Date(), '[Z] [ZZ]') // 'Z ZZ'
parseLoose
parseLoose(text: string, nativeFallback?: boolean) => Date | null
Parse common date forms. Values without a zone use local time; zoned values identify an instant. Native Date fallback is enabled by default; false accepts only the supported numeric forms. Invalid values return null.
import { parseLoose } from '@nscode/utils'
parseLoose('2026-11-19 09:05:03', false)
parseLoose('2026-11-19T01:05:03Z')
parseLoose('invalid', false) // null
parseDate
parseDate(text: string, format: string) => Date | null
Parse numeric format tokens and bracketed literals. Without an offset token, fields use local time. Z accepts Z or ±HH:mm; ZZ accepts Z or ±HHmm, converting the explicit offset into an instant. Offset hours range from 00 to 23 and minutes from 00 to 59. Mismatched shapes, invalid offsets, conflicting repeated offsets or nonexistent dates return null. [Z] and [ZZ] are literal text and do not mark a date as UTC.
YY maps to 2000–2099; omitted years use the current year, and other missing fields start at January 1, midnight. Complete x/X formats parse integer millisecond/second timestamps, including negative values and surrounding whitespace. Decimal, exponential or out-of-range values return null; [x] and [X] remain literals.
import { parseDate } from '@nscode/utils'
parseDate('2026/11/19 9:05', 'YYYY/MM/DD H:mm')
parseDate('2026-02-30', 'YYYY-MM-DD') // null
parseDate('2024-01-01T00:15:00+05:45', 'YYYY-MM-DDTHH:mm:ssZ')?.toISOString() // '2023-12-31T18:30:00.000Z'
parseDate('2023-12-31T15:00:00-0330', 'YYYY-MM-DDTHH:mm:ssZZ')?.toISOString() // Same instant as above
parseDate('2024-01-01T00:15:00+24:00', 'YYYY-MM-DDTHH:mm:ssZ') // null
isValidDate
isValidDate(value: unknown) => value is Date
Check for a valid Date instance; parsable strings are not Date objects.
import { isValidDate } from '@nscode/utils'
isValidDate(new Date()) // true
isValidDate(new Date(NaN)) // false
isValidDate('2026-11-19') // false