@superutils/core
A collection of lightweight, dependency-free utility functions and types.
Table of Contents
- Installation
- Usage
is: Type checkersdebounce(): Debounce callbacksthrottle(): Throttle callbacksdeferred(): Debounce/Throttle callbacksfallbackIfFails(): Gracefully invoke functions or promises with a fallbackobjCopy(): Deep-copy objectssearch(): Search iterable collections- Advanced search options
Ranked search: sort results by relevance- Combine
search()withdeferred(): simulate a search input with debounce mechanism
curry(): Convert any function into a curried function
Installation
npm install @superutils/coreUsage
is: type checkers
The is object provides a comprehensive set of type-checking functions.
import { is } from '@superutils/core'
is.fn(() => {}) // true
is.asyncFn(async () => {}) // true
is.arr([]) // true
is.arrLike([]) // true
is.arrLike(new Map()) // true
is.arrLike(new Set()) // true
is.date(new Date()) // true
is.date(new Date(undefined)) // false
is.empty(' ') // true
is.empty([]) // true
is.empty(new Map()) // true
is.empty(null) // true
is.empty(undefined) // true
is.map(new Map()) // true
is.number(123) // true
is.number(NaN) // false
is.url('https://google.com') // true
//...All these functions can also be imported independantly. Simply remove the dot (".") and uppercase the first letter of the function name.
import {
isArr,
isFn,
isArrLike,
isDate,
isEmpty,
isMap,
isNumber,
isUrl,
} from '@superutils/core'debouce(fn, delay, options): debounce callbacks
import { debouce } from '@superutils/core'
const handleChange = debouce(
event => console.log(event.target.value),
300, // debounce delay in milliseconds
{
leading: false, // default
},
)
handleChange({ target: { value: 1 } }) // will be ignored, unless `leading = true`
handleChange({ target: { value: 2 } }) // will be ignored
handleChange({ target: { value: 3 } }) // will be ignored
handleChange({ target: { value: 4 } }) // will be executedthrottle(fn, delay, options): throttle callbacks
import { throttle } from '@superutils/core'
const handleChange = throttle(
event => console.log(event.target.value),
300, // throttle duration in milliseconds
{
trailing: false, // default
},
)
handleChange({ target: { value: 1 } }) // will be executed
handleChange({ target: { value: 2 } }) // will be ignored
handleChange({ target: { value: 3 } }) // will be ignored
handleChange({ target: { value: 4 } }) // will be ignored, unless `trailing = true`deferred(fn, delay, options): debounce/throttle callbacks
Create debounced/throttled functions using the throttle switch.
import { deferred } from '@superutils/core'
const handleChange = deferred(
event => console.log(event.target.value),
300, // delay in milliseconds
{ throttle: false }, // determines whether to create a debounced or throttled function
)
handleChange({ target: { value: 1 } }) // will be ignored
handleChange({ target: { value: 2 } }) // will be ignored
handleChange({ target: { value: 3 } }) // will be executedfallbackIfFails(target, args, fallback): Gracefully invoke functions or promises with a fallback
The fallbackIfFails function can wrap a standard function, a promise-returning function, or a promise directly. It automatically handles both synchronous execution and asynchronous resolution, providing a fallback value if the function throws an error or the promise is rejected.
Sync operations:
import { fallbackIfFails } from '@superutils/core'
const allProducts = []
// an example sync function that may fail
const getProducts = () => {
if (!allProducts?.length) throw new Error('No products available')
return allProducts
}
const result = fallbackIfFails(
getProducts, // function to invoke
[], // Parameters to be provided to the function. A function can also be used here that returns an array
[], // Fallback value to be returned when function throws an error.
)
console.log({ result })
// Result: []Async operations:
import { fallbackIfFails } from '@superutils/core'
const allProducts = []
// an example sync function that may fail
const getProducts = () =>
fetch('https://dummyjson.com/products').then(r => r.json())
fallbackIfFails(
getProducts, // function to invoke
[], // Parameters to be provided to the function. A function can also be used here that returns an array
{ products: [] }, // Fallback value to be returned when function throws an error.
).then(console.log)
// Prints the result when request is successful or fallback value when request fails
// use a promise
fallbackIfFails(
Promise.reject('error'),
[], //
)objCopy(source, dest, ignoreKeys, override): deep-copy objects
import { objCopy } from '@superutils/core'
const source = {
a: 1,
b: 2,
c: 3,
}
const dest = {
d: 4,
e: 5,
}
const copied = objCopy(
source,
dest,
['a'], // exclude source property
'empty', // only override if dest doesn't have the property or value is "empty" (check `is.emtpy()`)
)
// Result:
// {
// b: 2,
// c: 33,
// d: 4,
// e: 5,
// }
console.log(dest === copied) // true (dest is returned)search(data, options): search iterable collections (Array/Map/Set)
import { search } from '@superutils/core'
// sample colletion
const data = new Map([
[1, { age: 30, name: 'Alice' }],
[2, { age: 25, name: 'Bob' }],
[3, { age: 35, name: 'Charlie' }],
[4, { age: 28, name: 'Dave' }],
[5, { age: 22, name: 'Eve' }],
])
// Case-insensitive search by name
search(data, { query: { name: 've' } })
search(data, { query: { name: /ve/i } }) // Using regular expression
// Result:
// new Map([
// [4, { age: 28, name: 'Dave' }],
// [5, { age: 22, name: 'Eve' }],
// ])
// Return result as Array
search(data, { asMap: false, query: { name: 've' } })
// Result: [
// { age: 28, name: 'Dave' },
// { age: 22, name: 'Eve' }
// ]
// Search multiple properties
search(data, { query: { age: 28, name: 've' } })
// Result:
// new Map([
// [4, { age: 28, name: 'Dave' }],
// ])
// Search across all properties
search(data, { query: 'li' })
search(data, { query: /li/i }) // Using regular expression
// Result:
// new Map([
// [1, { age: 30, name: 'Alice' }],
// [3, { age: 35, name: 'Charlie' }],
// ])Advanced Search Options:
import { search } from '@superutils/core'
// Sample colletion
const data = new Map([
[1, { age: 30, name: 'Alice' }],
[2, { age: 25, name: 'Bob' }],
[3, { age: 35, name: 'Charlie' }],
[4, { age: 28, name: 'Dave' }],
[5, { age: 22, name: 'Eve' }],
])
search(data, {
asMap: false, // Result type: true => Map (default, keys preserved), false => Array
ignoreCase: false, // For text case-sensitivity
limit: 10, // Number of items returned. Default: no limit
matchExact: true, // true: match exact value. false (default): partial matching
matchAll: true, // if true, item will be matched only when all of the query properties match
query: {
age: /(2[5-9])|(3[0-5])/, // match ages 25-35
name: /ali|ob|ve/i,
},
// transform the property values (or item itself when searching all properties in global search mode using `query: string | RegExp`)
transform: (item, value, property) => {
// exclude items by returning undefined or emptry string
if (item.age < 18) return ''
// return value as string to search continue search as per criteria
return `${value}`
},
})
// Result:
// [
// { age: 30, name: 'Alice' },
// { age: 25, name: 'Bob' },
// { age: 28, name: 'Dave' }
// ]Search Ranked: sort results by relevance
When ranked is set to true, results are sorted by relevance. In this example, "Alice" is ranked higher than "Charlie" because the match "li" appears earlier in the string.
import { search } from '@superutils/core'
// Sample colletion
const data = new Map([
[2, { age: 25, name: 'Bob' }],
[3, { age: 35, name: 'Charlie' }],
[4, { age: 28, name: 'Dave' }],
[5, { age: 22, name: 'Eve' }],
[1, { age: 30, name: 'Alice' }],
])
const result = search(data, {
asMap: false, // Result type: true => Map (default, keys preserved), false => Array
limit: 10, // Number of items returned. Default: no limit
query: /li/i,
ranked: true,
})
console.log(result)
// [ { age: 30, name: 'Alice' }, { age: 35, name: 'Charlie' } ]Combine search() with deferred(): simulate a search input with debounce mechanism
import { deferred, search } from '@superutils/core'
// sample colletion
const data = new Map([
[1, { age: 30, name: 'Alice' }],
[2, { age: 25, name: 'Bob' }],
[3, { age: 35, name: 'Charlie' }],
[4, { age: 28, name: 'Dave' }],
[5, { age: 22, name: 'Eve' }],
])
const searchDeferred = deferred(
event => {
const result = search(data, {
query: {
name: new RegExp(event?.target?.value, 'i'),
},
})
// print result to console
console.log(result)
},
300, // debounce duration in milliseconds
{ leading: false }, // optional defer options
)
// ignored
searchDeferred({ target: { value: 'l' } })
// ignored
setTimeout(() => searchDeferred({ target: { value: 'li' } }), 50)
// executed: prints `Map(1) { 3 => { age: 35, name: 'Charlie' } }`
setTimeout(() => searchDeferred({ target: { value: 'lie' } }), 200)
// executed: prints `Map(1) { 1 => { age: 30, name: 'Alice' } }`
setTimeout(() => searchDeferred({ target: { value: 'lic' } }), 510)curry(fn, arity): Convert any function into a curried function
const func = (
first: string,
second: number,
third?: boolean,
fourth?: string,
) => `${first}-${second}-${third}-${fourth}`
// We create a new function from the `func()` function that acts like a type-safe curry function
// while also being flexible with the number of arguments supplied.
const curriedFunc = curry(func)
// Example 1: usage like a regular curry function and provide one argument at a time.
// Returns a function expecting args: second, third, fourth
const fnWith1 = curriedFunc('first')
// Returns a function expecting args: third, fourth
const fnWith2 = fnWith1(2)
// returns a function epecting only fourth arg
const fnWith3 = fnWith2(false)
// All args are now provided, the original function is called and result is returned.
const result = fnWith3('last')Type Aliases
- ArrayComparator
- AsyncFn
- CreateTuple
- CurriedArgs
- Curry
- DebounceOptions
- DeferredOptions
- DropFirst
- DropFirstN
- DropLast
- EntryComparator
- FindOptions
- FiniteNumber
- IfPromiseAddValue
- Integer
- IsFiniteTuple
- IsOptional
- IterableList
- KeepFirst
- KeepFirstN
- KeepOptionals
- KeepRequired
- MakeOptional
- MinLength
- NegativeInteger
- NegativeNumber
- OptionalIf
- PositiveInteger
- PositiveNumber
- ReadOnlyAllowAddFn
- ReadOnlyConfig
- SearchOptions
- Slice
- SliceMapOptions
- SliceMapTransform
- SortOptions
- ThrottleOptions
- TimeoutId
- TupleMaxLength
- TupleWithAlt
- ValueOrFunc
- ValueOrPromise
Variables
Functions
- arrReadOnly
- arrReverse
- arrToMap
- arrUnique
- clearClutter
- copyToClipboard
- curry
- debounce
- deferred
- fallbackIfFails
- filter
- find
- getEntries
- getKeys
- getSize
- getUrlParam
- getValues
- isArr
- isArr2D
- isArrLike
- isArrLikeSafe
- isArrObj
- isArrUnique
- isAsyncFn
- isBool
- isDate
- isDateValid
- isDefined
- isEmpty
- isEmptySafe
- isEnvBrowser
- isEnvNode
- isEnvTouchable
- isError
- isFn
- isInteger
- isMap
- isMapObj
- isNegativeInteger
- isNegativeNumber
- isNumber
- isObj
- isPositiveInteger
- isPositiveNumber
- isPromise
- isRegExp
- isSet
- isStr
- isSubjectLike
- isSymbol
- isUint8Arr
- isUrl
- isUrlValid
- mapJoin
- matchObjOrProp
- noop
- noopAsync
- objClean
- objCopy
- objCreate
- objHasKeys
- objKeys
- objReadOnly
- objSetProp
- objSetPropUndefined
- objSort
- objWithoutKeys
- randomInt
- reverse
- search
- sliceMap
- sort
- strToArr
- throttle
- toDatetimeLocal