@jonathandelgado/utility v0.3.1
utility
Common utility library
alert(msg, meta)
Alert logger
Param | Type |
---|---|
msg | String |
meta | Error |
assert(condition, onlyIf, msg)
Asserts a condition, throws when the condition is unmet
Param | Type | Default | Description |
---|---|---|---|
condition | Boolean | ||
onlyIf | Boolean | If this equals false , the condition is ignored, useful for something like isDefined | |
msg | String | Assertion Error |
asyncify(func) => function
Creates an async function that is called next tick
Param | Type |
---|---|
func | function |
attempt(value, ...args) => *
Attempts to run func
within a try block, returning an error or the result
Param | Type |
---|---|
value | function |
...args | * |
avg(arr) => Number
Averages an array of values
Param | Type | Description |
---|---|---|
arr | Array.<Number> | Cannot be empty |
bindClass(scope, traverse)
Binds a class's functions to the parent class
Param | Type | Description |
---|---|---|
scope | Object | |
traverse | Boolean | Object | true to traverse extended classes |
callWith(func, ...args) => function
Creates a wrapper function with arguments pre-set, arguments passed at runtime are appended to the args
Param | Type |
---|---|
func | function |
...args | * |
capitalize(value) => String
Capitalizes each word of a string
Param | Type |
---|---|
value | String |
chop(value, len) => Array.<String>
Chops value
every len
characters
Param | Type | Description |
---|---|---|
value | String | |
len | Number | > 0 |
clone(value) => Array | Object
Creates an exact copy of an object without references, this doesn't affect instanced items such as dates
Param | Type |
---|---|
value | Array | Object |
consts
Constants for second
, minute
, hour
, day
, week
, month
and year
contains(value, item) => Boolean
Determines if value
contains item
Param | Type |
---|---|
value | Array | String |
item | * |
count(value, item) => Number
Counts the occurances of item
in value
Param | Type |
---|---|
value | Array | String |
item | * |
counter(max) => function
High resolution counter
Returns: function - () => Number
Param | Type | Default | Description |
---|---|---|---|
max | Number | Number.MAX_VALUE | >= 0, Will cause the counter to reset after this limit is inclusively hit. |
debug(msg, meta)
Debug logger
Param | Type |
---|---|
msg | String |
meta | * |
dedent(str) => String
Removes indentation from strings, so newlines have no starting whitespace
Param | Type |
---|---|
str | String |
defaultTo(val, def) => *
Returns def
if val
is undefined
, otherwise returns val
. If val
and
def
are both objects, will merge val
into def
Param | Type |
---|---|
val | * |
def | * |
diffArray(a, b) => Object
Determines which elements were added and removed between two arrays - must be shallow non-object keys
Returns: Object - Contains add
and rem
keys, both are arrays
Param | Type |
---|---|
a | Array |
b | Array |
diffObject(a, b, bail, ns) => Array.<String>
Determines which keys were changed between two objects
Param | Type | Description |
---|---|---|
a | * | |
b | * | |
bail | Boolean | Stop on the first difference detected |
ns | String | For recursion |
endsWith(value, option) => Boolean
Determines if value
ends with option
Param | Type |
---|---|
value | String |
option | String |
enumerable(value) => Object
Creates an enumerable object
Param | Type | Description |
---|---|---|
value | Array.<String> | Must be uppercase values, cannot be empty |
enums
Enumberables for various functions, containing alpha
, hex
, etc
error(msg, meta)
Error logger
Param | Type |
---|---|
msg | String |
meta | Error |
escape(value) => String
Sanitizes value by escaping the string
Param | Type |
---|---|
value | String |
filter(value, iter) => Array
Filters an array using an iterator
Param | Type | Description |
---|---|---|
value | Array | |
iter | function | Object | String | (value, idx) => Boolean |
find(value, len, reverse, iter, noClone) => *
Finds and clones matches from an array
Returns: * - If len
is not 1
, will return an array, otherwise, it will
return the first result or undefined
Param | Type | Default | Description |
---|---|---|---|
value | Array | ||
len | Number | 1 | >= 1 |
reverse | Boolean | false | |
iter | function | Object | String | (value, idx) => Boolean | |
noClone | Boolean | false |
forceLength(value, len, lead) => String
Forces a string length by adding a leading value
Param | Type | Default | Description |
---|---|---|---|
value | String | ||
len | Number | >= 0 | |
lead | String | 0 |
forceWithin(value, min, max) => Number
Ensures value
is within min
and max
inclusively
Param | Type | Description |
---|---|---|
value | Number | |
min | Number | < max |
max | Number | > min |
forEach(value, reverse, iter)
Iterates over an array or object
Param | Type | Default | Description |
---|---|---|---|
value | Array | Object | ||
reverse | Boolean | false | |
iter | function | (key, val, idx) |
forEachAwait(value, limit, reverse, iter) => *
Iterate over an array or object, but can be used with await
Returns: * - If iter
returns a value, the loop is broken and that value is
returned here, otherwise, undefined
Param | Type | Default | Description |
---|---|---|---|
value | Array | Object | ||
limit | Number | 1 | >= 0 |
reverse | Boolean | false | |
iter | function | (key, val, idx) => Promise |
forNum(len, reverse, iter) => *
Sugared for loop
Returns: * - If iter
returns a value, the loop is broken and that value is
returned here, otherwise, undefined
Param | Type | Default | Description |
---|---|---|---|
len | Number | >= 0 | |
reverse | Boolean | false | |
iter | function | (idx) => Boolean/undefined |
forNumAwait(len, limit, reverse, iter) => *
Sugared for loop, but can be used with await
Returns: * - If iter
returns a value, the loop is broken and that value is
returned here, otherwise, undefined
Param | Type | Default | Description |
---|---|---|---|
len | Number | >= 0 | |
limit | Number | 1 | >= 0 |
reverse | Boolean | false | |
iter | function | (idx) => Promise |
forUntil(value, reverse, iter) => *
Iterates over an array or object, stopping when something is returned
Returns: * - If iter
returns a value, the loop is broken and that value is
returned here, otherwise, undefined
Param | Type | Default | Description |
---|---|---|---|
value | Array | Object | ||
reverse | Boolean | false | |
iter | function | (key, val, idx) => {*} |
forUntilAwait(value, limit, reverse, iter) => *
Iterate over an array or object, stopping when something is returned, but can be used with await
Returns: * - If iter
returns a value, the loop is broken and that value is
returned here, otherwise, undefined
Param | Type | Default | Description |
---|---|---|---|
value | Array | Object | ||
limit | Number | 1 | >= 0 |
reverse | Boolean | false | |
iter | function | (key, val, idx) => Promise |
get(obj, ns) => *
Gets a property from an object using a namespace
Param | Type |
---|---|
obj | Object |
ns | Array | String |
getArgs() => Object
Gets the parsed arguments provided to the process
Returns: Object - Arguments without a flag will be in an array in the _
key
getEnv(key) => *
Gets an enviornment variable provided to the process
Param | Type |
---|---|
key | String |
group(value, iter) => Object
Groups an array based on iterator input
Param | Type | Description |
---|---|---|
value | Array | |
iter | function | String | (key, idx) => * |
has(obj, ns) => Boolean
Determines if an object has a value at the namespace address
Param | Type |
---|---|
obj | Object |
ns | Array | String |
humanize(value) => String
Humanizes a string by capitalizing the first letter and lowercasing the rest
Param | Type |
---|---|
value | String |
info(msg, meta)
Info logger
Param | Type |
---|---|
msg | String |
meta | * |
isAll(value, iter) => Boolean
Determines if value
all pass iter
Param | Type | Description |
---|---|---|
value | Array | Cannot be empty |
iter | Array | function |
isAlpha(value) => Boolean
Determines if value
only has alphabetical characters
Param | Type |
---|---|
value | String |
isAlphanumeric(value) => Boolean
Determines if value
only has alphanumeric characters
Param | Type |
---|---|
value | String |
isArray(value) => Boolean
Determines if value
is an array
Param | Type |
---|---|
value | Array |
isAscii(value) => Boolean
Determines if value
only has ASCII characters
Param | Type |
---|---|
value | String |
isBoolean(value) => Boolean
Determines if value
is a boolean
Param | Type |
---|---|
value | Boolean |
isBrowser() => Boolean
Determines if environment is a browser
isDate(value) => Boolean
Determines if value
is a valid date
Param | Type |
---|---|
value | Date |
isDecimal(value, dec) => Boolean
Determines if value
is a number with a dec
Param | Type | Default | Description |
---|---|---|---|
value | * | ||
dec | String | . | Decimal mark to use |
isDeepEqual(a, b) => Boolean
Determines if a
is deeply equal to b
Param | Type |
---|---|
a | * |
b | * |
isDefined(value) => Boolean
Determines if value
has been defined
Param | Type |
---|---|
value | * |
isDivisibleBy(value, option) => Boolean
Determines if value
is divisible by option
Param | Type |
---|---|
value | Number |
option | Number |
isEach(value, iter) => Boolean
Determines if value
passes each of the iter
validations
Param | Type |
---|---|
value | * |
iter | Array.<function()> |
isEmail(value) => Boolean
Determines if value
is an email
Param | Type |
---|---|
value | String |
isEmpty(value) => Boolean
Determines if a value
is empty
Param | Type |
---|---|
value | * |
isEqual(value, option) => Boolean
Determines if value
equals option
Param | Type |
---|---|
value | * |
option | * |
isError(value) => Boolean
Determines if value
is an error
Param | Type |
---|---|
value | Error |
isEven(value) => Boolean
Determines if value
is even
Param | Type |
---|---|
value | Number |
isFloat(value, dec) => Boolean
Determines if value
is a float
Param | Type | Default | Description |
---|---|---|---|
value | * | ||
dec | String | . | Decimal mark to use |
isFunction(value) => Boolean
Determines if value
is a function
Param | Type |
---|---|
value | function |
isGt(value, option) => Boolean
Determines if value
is greater than option
Param | Type |
---|---|
value | Number |
option | Number |
isGtEq(value, option) => Boolean
Determines if value
is greater than or equal to option
Param | Type |
---|---|
value | Number |
option | Number |
isHex(value) => Boolean
Determines if value
is a hex value
Param | Type |
---|---|
value | String |
isHexColor(value) => Boolean
Determines if value
is a hex color
Param | Type |
---|---|
value | String |
isInt(value) => Boolean
Determines if value
is an integer
Param | Type |
---|---|
value | String |
isIP(value) => Boolean
Determines if value
is an IP, v4 or v6
Param | Type |
---|---|
value | String |
isIPv4(value) => Boolean
Determines if value
is an IP, v4
Param | Type |
---|---|
value | String |
isIPv6(value) => Boolean
Determines if value
is an IP, v6
Param | Type |
---|---|
value | String |
isLengthWithin(value, min, max) => Boolean
Determines if value
has a length within min
and max
Param | Type |
---|---|
value | * |
min | Number |
max | Number |
isLower(value) => Boolean
Determines if value
is completely lowercase
Param | Type |
---|---|
value | String |
isLt(value, option) => Boolean
Determines if value
is less than option
Param | Type |
---|---|
value | Number |
option | Number |
isLtEq(value, option) => Boolean
Determines if value
is less than or equal to option
Param | Type |
---|---|
value | Number |
option | Number |
isMatch(value, option) => Boolean
Determines if value
matches regex
Param | Type |
---|---|
value | String |
option | RegExp | String |
isNil(value) => Boolean
Determines if value
is null or undefined
Param | Type |
---|---|
value | * |
isNull(value) => Boolean
Determines if value
is null
Param | Type |
---|---|
value | * |
isNumber(value) => Boolean
Determines if value
is a number
Param | Type |
---|---|
value | Number |
isNumeric(value) => Boolean
Determines if value
is strictly numeric
Param | Type |
---|---|
value | String |
isObject(value) => Boolean
Determines if value
is an object
Param | Type |
---|---|
value | Object |
isPlainObject(value) => Boolean
Determines if value
is a non-instance object
Param | Type |
---|---|
value | Object |
isProduction() => Boolean
Determines if environment is in production
isPromise(value) => Boolean
Determines if value
is a Promise
Param | Type |
---|---|
value | Promise |
isRegExp(value) => Boolean
Determines if value
is a RegExp
Param | Type |
---|---|
value | RegExp |
isSlug(value) => Boolean
Determines if value
only has slug safe characters
Param | Type |
---|---|
value | String |
isString(value) => Boolean
Determines if value
is a string
Param | Type |
---|---|
value | String |
isTid(value) => Boolean
Determines if value
is a valid tid
Param | Type |
---|---|
value | String |
isUpper(value) => Boolean
Determines if value
is completely uppercase
Param | Type |
---|---|
value | String |
isUrl(value) => Boolean
Determines if value
is a valid URL
Param | Type |
---|---|
value | String |
isValidJSON(value) => Boolean
Determines if value
is valid JSON
Param | Type |
---|---|
value | String |
isValidRegExp(value) => Boolean
Determines if value
is a valid RegExp
Param | Type |
---|---|
value | String |
isWithin(value, min, max) => Boolean
Determines if value
is within min
and max
Param | Type |
---|---|
value | Number |
min | Number |
max | Number |
join(value, by=) => String
Joins an array
Param | Type | Description |
---|---|---|
value | Array | |
by= | String | Can provide an enums SPACE, COMMA and LINE or a custom join string |
keys(value) => Array.<String>
Gets an array of keys from an object
Param | Type |
---|---|
value | Array | Object |
limitArgs(func, len) => function
Limits the amount of arguments a function gets
Param | Type | Description |
---|---|---|
func | function | |
len | Number | >= 0 |
limitCalls(func, len) => function
Limits the amount of times a function can be called
Param | Type | Description |
---|---|---|
func | function | |
len | Number | >= 0 |
map(value, reverse, iter) => Array | Object
Iterates over an array or object and maps the results
Param | Type | Default | Description |
---|---|---|---|
value | Array | Object | ||
reverse | Boolean | false | |
iter | function | String | (key, val, idx) => * |
mapAwait(value, limit, reverse, iter) => Array | Object
Iterates over an array or object and maps the results, but can be used with await
Param | Type | Default | Description |
---|---|---|---|
value | Array | Object | ||
limit | Number | 1 | >= 0 |
reverse | Boolean | false | |
iter | function | (key, val, idx) => Promise |
max(value) => Number
Reduces an array by getting the max value
Param | Type | Description |
---|---|---|
value | Array.<Number> | Cannot be empty |
merge(dst, src) => Object | Array
Merges two objects together to the dst
object, if the dst
is not an
object, it will consolidate all arguments into a single array
Param | Type |
---|---|
dst | Object |
src | Object |
metric(key, val)
Collects metrics for log propogation
Param | Type |
---|---|
key | String |
val | Object |
min(value) => Number
Reduces an array by getting the min value
Param | Type | Description |
---|---|---|
value | Array.<Number> | Cannot be empty |
namespace(ns, append, toString) => Array | String
Creates a namespace array
Param | Type | Default |
---|---|---|
ns | Array | String | |
append | Array | String | |
toString | Boolean | false |
noop()
A no-operation function
parseCurrency(value, dec) => Number
Parses value
to currency
Param | Type | Default |
---|---|---|
value | Number | String | |
dec | String | . |
parsePhone(value) => String
Parses an irregular value
to a phone number
Param | Type |
---|---|
value | String |
percentile(value, percentile) => Number
Gets the percentile of a number array
Param | Type | Description |
---|---|---|
value | Array.<Number> | Cannot be empty |
percentile | Number | 0..100 |
promisify(func) => function
Turns a callback function into a promise
Returns: function - Will now return a promise instead of using callbacks
Param | Type |
---|---|
func | function |
promisifyAll(obj) => Object
Iterates over an Object and creates a copy with promisified functions,
non-function and functions ending in Sync
will be skipped
Param | Type |
---|---|
obj | Object |
pushCap(value, max, item) => Number
Pushes to a capped collection
Param | Type |
---|---|
value | Array |
max | Number |
item | * |
queue(func, limit) => Object
Creates a queue for a function, limits how many instances are running at once
Returns: Object - New queue instance, with an add
and isRunning
function
as well as a pending
array
Param | Type | Default | Description |
---|---|---|---|
func | function | ||
limit | Number | 1 | >= 1 |
random(min, max) => Number
Generate a random number between and including min
and max
Param | Type | Description |
---|---|---|
min | Number | < max |
max | Number | > min |
randomBlock(len, dict) => String
Generate a random block of characters
Param | Type | Description |
---|---|---|
len | Number | >= 0 |
dict | String | Can provide an enums NUM, HEX, ALPHA or ALPHANUM or a custom dict |
range(min, max, inc) => Array.<Number>
Creates a range of numbers between min
and max
Param | Type | Default | Description |
---|---|---|---|
min | Number | < max | |
max | Number | > min | |
inc | Number | 1 | > 0 |
reduce(value, reverse, iter, initial) => *
Iterates over an array or object to create a single value
Param | Type | Default | Description |
---|---|---|---|
value | Array | Object | ||
reverse | Boolean | false | |
iter | function | (res, key, val, idx) => * | |
initial | * | 0 |
reduceAwait(value, reverse, iter, initial) => Promise
Iterates over an array of object to create a single value, but can be used with await
Param | Type | Default | Description |
---|---|---|---|
value | Array | Object | ||
reverse | Boolean | false | |
iter | function | (res, key, val, idx) => Promise | |
initial | * | 0 |
repeat(value, len) => String
Repeats value
len
amount of times
Param | Type | Description |
---|---|---|
value | * | |
len | Number | >= 0 |
replace(value, regex, text=) => String
Replaces regex
matches of value
with text
Param | Type |
---|---|
value | String |
regex | RegExp | String |
text= | String |
sample(value, len) => *
Shuffles and returns len
items
Returns: * - Will return a single item if len
is 1
, otherwise an Array
Param | Type | Default | Description |
---|---|---|---|
value | Array | ||
len | Number | 1 | >= 1 |
set(obj, ns, value) => *
Sets a property in an object using a namespace
Param | Type |
---|---|
obj | Object |
ns | Array | String |
value | * |
setIntervalAndRun(func, interval)
Creates an interval and runs the function immediately
Param | Type |
---|---|
func | function |
interval | Number |
shuffle(value) => Array
Shuffles an array
Param | Type |
---|---|
value | Array |
size(value, lastIndex) => Number
Gets the length of an array or object
Param | Type | Description |
---|---|---|
value | Array | Object | |
lastIndex | Boolean | Denotes if the returned value should be the last index of the array instead of the length |
slice(value, idx, len) => Array | String
Slices a string or array at idx
Param | Type | Description |
---|---|---|
value | Array | String | |
idx | Number | Index to start, if negative, will start at the end |
len | Number | Length of the slice, if negative it will slice from idx to value.length - (-len) |
slugify(value) => String
Turns a string into a valid URL slug
Param | Type |
---|---|
value | String |
sort(value, reverse, by) => Array
Sorts an array by a single or array of keys
Param | Type | Default | Description |
---|---|---|---|
value | Array | ||
reverse | Boolean | false | |
by | Array | String | * | Specifying * denotes a shallow item, items starting with a - will be reverse sorted |
split(value, by=) => Array.<String>
Splits a string into an array
Param | Type | Description |
---|---|---|
value | String | |
by= | String | Can provide an enums SPACE, COMMA and LINE or a custom join string |
spread(value, len, run) => Array
Generates a spread array using value
Param | Type | Default | Description |
---|---|---|---|
value | * | ||
len | Number | >= 0 | |
run | Boolean | isFunction(value) | Will run value before using it |
startsWith(value, option) => Boolean
Determines if value
starts with option
Param | Type |
---|---|
value | String |
option | String |
sum(value) => Number
Reduce an array by adding the values
Param | Type | Description |
---|---|---|
value | Array.<Number> | Cannot be empty |
template(value, scope) => String
Templates out value
using variables declared in the scope
object
Param | Type |
---|---|
value | String |
scope | Object |
throttle(func, time, debounce) => function
Throttles or debounces a function
Param | Type | Default | Description |
---|---|---|---|
func | function | ||
time | Number | >= 0 | |
debounce | Boolean | false | In this mode, new calls will reset the timer, this prevents function being called until the timeout is reached |
tid(date) => String
Creates a new time id
Param | Type | Default |
---|---|---|
date | Date | Number | String | Date.now() |
timeout(promise, time) => Promise
Creates a timeout for a promise
Param | Type | Description |
---|---|---|
promise | Promise | |
time | Number | >= 0 |
timer() => function
Creates a running timer
Returns: function - () => Number, returns the duration
toArray(value) => Array
Ensures value
is an array, slices arguments
Param | Type |
---|---|
value | * |
toBool(value) => Boolean
Converts value
to a boolean
Param | Type |
---|---|
value | * |
toDate(value, fromUnix) => Date
Converts value
to a date
Param | Type | Default | Description |
---|---|---|---|
value | * | ||
fromUnix | Boolean | false | Denotes if the value is UNIX, which requires a millisecond conversion |
toLower(value) => String
Converts value
to lowercase
Param | Type |
---|---|
value | String |
toNumber(value, dec) => Number
Converts value
to a number
Param | Type | Default |
---|---|---|
value | * | |
dec | String | . |
toString(value) => String
Converts value
to a string
Param | Type |
---|---|
value | * |
toUnix(value) => Number
Converts value
to a UNIX timestamp
Param | Type |
---|---|
value | Date | Number | String |
toUpper(value) => String
Converts value
to uppercase
Param | Type |
---|---|
value | String |
traverseObj(obj, ns, isSet, value) => *
Traverses an object using a namespace and get/set's the corresponding key
Param | Type | Default |
---|---|---|
obj | Object | |
ns | Array | String | |
isSet | Boolean | false |
value | * |
trim(value, regex) => String
Trims value
of whitespace or regex
Param | Type |
---|---|
value | String |
regex | RegExp |
trimInner(value) => String
Trims and consolidates all whitespace in value
Param | Type |
---|---|
value | String |
trunc(value, len, ellipsis) => String
Truncates value
at len
Param | Type | Default | Description |
---|---|---|---|
value | String | ||
len | Number | >= 0 | |
ellipsis | String | ... |
unescape(value) => String
Reverses an escaped string
Param | Type |
---|---|
value | String |
unique(value, iter) => Array
Ensures all mapped values are unique, eliminating duplicates
Param | Type | Description |
---|---|---|
value | Array | |
iter | function | String | (key, idx) => Boolean |
values(value) => Array
Returns an array of object values
Param | Type |
---|---|
value | Object |
verbose(msg, meta)
Verbose logger
Param | Type |
---|---|
msg | String |
meta | Error |
wait(time) => Promise
A simple timeout using await
Param | Type | Description |
---|---|---|
time | Number | >= 0 |
waitUntil(func, args) => Promise
Waits until func
returns true
Param | Type | Default | Description |
---|---|---|---|
func | function | () => Boolean, Will be rerun every args.interval , if returns true , will exit the wait | |
args | Object | ||
args.interval | Number | 1000 | >= 0 |
args.timeout | Number | 60000 | >= 0 |
warn(msg, meta)
Warn logger
Param | Type |
---|---|
msg | String |
meta | Error |
words(value) => Array.<String>
Converts a string into an array of words
Param | Type |
---|---|
value | String |