@devindex/utils
v1.2.0
Published
A collection of JavaScript utility functions
Readme
@devindex/utils
A collection of JavaScript utility functions for any runtime.
Installation
npm install @devindex/utilsUsage
// Import a specific module
import { array, string, crypto } from '@devindex/utils';
array.first([1, 2, 3]); // 1
string.capitalize('hello world'); // "Hello World"
crypto.random(); // "a1b2c3d4e5"
// Or import directly from a module
import { first, last } from '@devindex/utils/array';
import { capitalize } from '@devindex/utils/string';Modules
array
asyncForEach(array, callback)— async iterationsortBy(items, field, desc?)— sort array of objects by fieldfirst(items, defaultValue?)— first element or defaultlast(items, defaultValue?)— last element or defaultensureArray(items, defaultValue?)— return array or defaulthasItems(items)— check if array has elements
boolean
toBoolean(value)— convert value to boolean ('true','yes','1',1→true)parse(value)— deprecated alias oftoBoolean, will be removed in the next major version
crypto
random(size?)— random hex stringbtoa(str)— base64 encodeatob(str)— base64 decodemd5(str)— MD5 hash
env
getValue(name, defaults?)— get env variable with fallback
http
request(url, options?)— fetch wrapper with error checking and parsed response (options.responseType:'json'|'text'|'blob'|'arrayBuffer', default'json')get(url, options?)— GET requestpost(url, body, options?)— POST request with JSON bodyput(url, body, options?)— PUT request with JSON bodypatch(url, body, options?)— PATCH request with JSON bodydel(url, options?)— DELETE request (also exported asdeletefor namespaced usage:http.delete(...))normalizeURLProtocol(url)— prependhttps:to protocol-relative URLsgetAsArrayBuffer(url, options?)— fetch URL as ArrayBuffergetPDFAsArrayBuffer(url)— fetch PDF as ArrayBuffergetImageAsArrayBuffer(url)— fetch image as ArrayBuffer
number
round(value, precision?)— round to precision
object
fillFields(fields, source, target)— copy specific fields from source to targetisEmpty(obj)— check if object has no keysreplaceProperty(obj, from, to)— rename a single propertyreplaceProperties(obj, props)— rename multiple properties
stream
toBuffer(stream)— convert readable stream to Buffer
string
hexToBase64(str)/base64ToHex(str)— encoding conversionsanitizeDigits(value, defaultValue?)— extract digits onlysanitizeChars(text)— remove special charactersremoveAccents(text)— remove diacriticsescapeRegex(str)— escape regex special charscapitalize(value, skipTerms?)— capitalize wordscapitalizeWord(word)— capitalize single wordcapitalizeNameBR(value)— capitalize Brazilian namescapitalizeFirst(value)— capitalize first letter onlyslugify(value)— convert to a URL-friendly slugtruncate(value, max)— truncate tomaxchars, ellipsis includedparsePhoneBR(phone, defaultDDD?)— normalize Brazilian phone
terminal
getArgs()— parse CLI argumentsexecute(fn)— run async function with error handling
License
MIT
