0.3.1 • Published 6 years ago

@jonathandelgado/utility v0.3.1

Weekly downloads
-
License
UNLICENSED
Repository
github
Last release
6 years ago

utility

Common utility library

alert(msg, meta)

Alert logger

ParamType
msgString
metaError

assert(condition, onlyIf, msg)

Asserts a condition, throws when the condition is unmet

ParamTypeDefaultDescription
conditionBoolean
onlyIfBooleanIf this equals false, the condition is ignored, useful for something like isDefined
msgStringAssertion Error

asyncify(func) => function

Creates an async function that is called next tick

ParamType
funcfunction

attempt(value, ...args) => *

Attempts to run func within a try block, returning an error or the result

ParamType
valuefunction
...args*

avg(arr) => Number

Averages an array of values

ParamTypeDescription
arrArray.<Number>Cannot be empty

bindClass(scope, traverse)

Binds a class's functions to the parent class

ParamTypeDescription
scopeObject
traverseBoolean | Objecttrue 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

ParamType
funcfunction
...args*

capitalize(value) => String

Capitalizes each word of a string

ParamType
valueString

chop(value, len) => Array.<String>

Chops value every len characters

ParamTypeDescription
valueString
lenNumber> 0

clone(value) => Array | Object

Creates an exact copy of an object without references, this doesn't affect instanced items such as dates

ParamType
valueArray | Object

consts

Constants for second, minute, hour, day, week, month and year

contains(value, item) => Boolean

Determines if value contains item

ParamType
valueArray | String
item*

count(value, item) => Number

Counts the occurances of item in value

ParamType
valueArray | String
item*

counter(max) => function

High resolution counter

Returns: function - () => Number

ParamTypeDefaultDescription
maxNumberNumber.MAX_VALUE>= 0, Will cause the counter to reset after this limit is inclusively hit.

debug(msg, meta)

Debug logger

ParamType
msgString
meta*

dedent(str) => String

Removes indentation from strings, so newlines have no starting whitespace

ParamType
strString

defaultTo(val, def) => *

Returns def if val is undefined, otherwise returns val. If val and def are both objects, will merge val into def

ParamType
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

ParamType
aArray
bArray

diffObject(a, b, bail, ns) => Array.<String>

Determines which keys were changed between two objects

ParamTypeDescription
a*
b*
bailBooleanStop on the first difference detected
nsStringFor recursion

endsWith(value, option) => Boolean

Determines if value ends with option

ParamType
valueString
optionString

enumerable(value) => Object

Creates an enumerable object

ParamTypeDescription
valueArray.<String>Must be uppercase values, cannot be empty

enums

Enumberables for various functions, containing alpha, hex, etc

error(msg, meta)

Error logger

ParamType
msgString
metaError

escape(value) => String

Sanitizes value by escaping the string

ParamType
valueString

filter(value, iter) => Array

Filters an array using an iterator

ParamTypeDescription
valueArray
iterfunction | 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

ParamTypeDefaultDescription
valueArray
lenNumber1>= 1
reverseBooleanfalse
iterfunction | Object | String(value, idx) => Boolean
noCloneBooleanfalse

forceLength(value, len, lead) => String

Forces a string length by adding a leading value

ParamTypeDefaultDescription
valueString
lenNumber>= 0
leadString0

forceWithin(value, min, max) => Number

Ensures value is within min and max inclusively

ParamTypeDescription
valueNumber
minNumber< max
maxNumber> min

forEach(value, reverse, iter)

Iterates over an array or object

ParamTypeDefaultDescription
valueArray | Object
reverseBooleanfalse
iterfunction(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

ParamTypeDefaultDescription
valueArray | Object
limitNumber1>= 0
reverseBooleanfalse
iterfunction(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

ParamTypeDefaultDescription
lenNumber>= 0
reverseBooleanfalse
iterfunction(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

ParamTypeDefaultDescription
lenNumber>= 0
limitNumber1>= 0
reverseBooleanfalse
iterfunction(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

ParamTypeDefaultDescription
valueArray | Object
reverseBooleanfalse
iterfunction(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

ParamTypeDefaultDescription
valueArray | Object
limitNumber1>= 0
reverseBooleanfalse
iterfunction(key, val, idx) => Promise

get(obj, ns) => *

Gets a property from an object using a namespace

ParamType
objObject
nsArray | 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

ParamType
keyString

group(value, iter) => Object

Groups an array based on iterator input

ParamTypeDescription
valueArray
iterfunction | String(key, idx) => *

has(obj, ns) => Boolean

Determines if an object has a value at the namespace address

ParamType
objObject
nsArray | String

humanize(value) => String

Humanizes a string by capitalizing the first letter and lowercasing the rest

ParamType
valueString

info(msg, meta)

Info logger

ParamType
msgString
meta*

isAll(value, iter) => Boolean

Determines if value all pass iter

ParamTypeDescription
valueArrayCannot be empty
iterArray | function

isAlpha(value) => Boolean

Determines if value only has alphabetical characters

ParamType
valueString

isAlphanumeric(value) => Boolean

Determines if value only has alphanumeric characters

ParamType
valueString

isArray(value) => Boolean

Determines if value is an array

ParamType
valueArray

isAscii(value) => Boolean

Determines if value only has ASCII characters

ParamType
valueString

isBoolean(value) => Boolean

Determines if value is a boolean

ParamType
valueBoolean

isBrowser() => Boolean

Determines if environment is a browser

isDate(value) => Boolean

Determines if value is a valid date

ParamType
valueDate

isDecimal(value, dec) => Boolean

Determines if value is a number with a dec

ParamTypeDefaultDescription
value*
decString.Decimal mark to use

isDeepEqual(a, b) => Boolean

Determines if a is deeply equal to b

ParamType
a*
b*

isDefined(value) => Boolean

Determines if value has been defined

ParamType
value*

isDivisibleBy(value, option) => Boolean

Determines if value is divisible by option

ParamType
valueNumber
optionNumber

isEach(value, iter) => Boolean

Determines if value passes each of the iter validations

ParamType
value*
iterArray.<function()>

isEmail(value) => Boolean

Determines if value is an email

ParamType
valueString

isEmpty(value) => Boolean

Determines if a value is empty

ParamType
value*

isEqual(value, option) => Boolean

Determines if value equals option

ParamType
value*
option*

isError(value) => Boolean

Determines if value is an error

ParamType
valueError

isEven(value) => Boolean

Determines if value is even

ParamType
valueNumber

isFloat(value, dec) => Boolean

Determines if value is a float

ParamTypeDefaultDescription
value*
decString.Decimal mark to use

isFunction(value) => Boolean

Determines if value is a function

ParamType
valuefunction

isGt(value, option) => Boolean

Determines if value is greater than option

ParamType
valueNumber
optionNumber

isGtEq(value, option) => Boolean

Determines if value is greater than or equal to option

ParamType
valueNumber
optionNumber

isHex(value) => Boolean

Determines if value is a hex value

ParamType
valueString

isHexColor(value) => Boolean

Determines if value is a hex color

ParamType
valueString

isInt(value) => Boolean

Determines if value is an integer

ParamType
valueString

isIP(value) => Boolean

Determines if value is an IP, v4 or v6

ParamType
valueString

isIPv4(value) => Boolean

Determines if value is an IP, v4

ParamType
valueString

isIPv6(value) => Boolean

Determines if value is an IP, v6

ParamType
valueString

isLengthWithin(value, min, max) => Boolean

Determines if value has a length within min and max

ParamType
value*
minNumber
maxNumber

isLower(value) => Boolean

Determines if value is completely lowercase

ParamType
valueString

isLt(value, option) => Boolean

Determines if value is less than option

ParamType
valueNumber
optionNumber

isLtEq(value, option) => Boolean

Determines if value is less than or equal to option

ParamType
valueNumber
optionNumber

isMatch(value, option) => Boolean

Determines if value matches regex

ParamType
valueString
optionRegExp | String

isNil(value) => Boolean

Determines if value is null or undefined

ParamType
value*

isNull(value) => Boolean

Determines if value is null

ParamType
value*

isNumber(value) => Boolean

Determines if value is a number

ParamType
valueNumber

isNumeric(value) => Boolean

Determines if value is strictly numeric

ParamType
valueString

isObject(value) => Boolean

Determines if value is an object

ParamType
valueObject

isPlainObject(value) => Boolean

Determines if value is a non-instance object

ParamType
valueObject

isProduction() => Boolean

Determines if environment is in production

isPromise(value) => Boolean

Determines if value is a Promise

ParamType
valuePromise

isRegExp(value) => Boolean

Determines if value is a RegExp

ParamType
valueRegExp

isSlug(value) => Boolean

Determines if value only has slug safe characters

ParamType
valueString

isString(value) => Boolean

Determines if value is a string

ParamType
valueString

isTid(value) => Boolean

Determines if value is a valid tid

ParamType
valueString

isUpper(value) => Boolean

Determines if value is completely uppercase

ParamType
valueString

isUrl(value) => Boolean

Determines if value is a valid URL

ParamType
valueString

isValidJSON(value) => Boolean

Determines if value is valid JSON

ParamType
valueString

isValidRegExp(value) => Boolean

Determines if value is a valid RegExp

ParamType
valueString

isWithin(value, min, max) => Boolean

Determines if value is within min and max

ParamType
valueNumber
minNumber
maxNumber

join(value, by=) => String

Joins an array

ParamTypeDescription
valueArray
by=StringCan provide an enums SPACE, COMMA and LINE or a custom join string

keys(value) => Array.<String>

Gets an array of keys from an object

ParamType
valueArray | Object

limitArgs(func, len) => function

Limits the amount of arguments a function gets

ParamTypeDescription
funcfunction
lenNumber>= 0

limitCalls(func, len) => function

Limits the amount of times a function can be called

ParamTypeDescription
funcfunction
lenNumber>= 0

map(value, reverse, iter) => Array | Object

Iterates over an array or object and maps the results

ParamTypeDefaultDescription
valueArray | Object
reverseBooleanfalse
iterfunction | 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

ParamTypeDefaultDescription
valueArray | Object
limitNumber1>= 0
reverseBooleanfalse
iterfunction(key, val, idx) => Promise

max(value) => Number

Reduces an array by getting the max value

ParamTypeDescription
valueArray.<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

ParamType
dstObject
srcObject

metric(key, val)

Collects metrics for log propogation

ParamType
keyString
valObject

min(value) => Number

Reduces an array by getting the min value

ParamTypeDescription
valueArray.<Number>Cannot be empty

namespace(ns, append, toString) => Array | String

Creates a namespace array

ParamTypeDefault
nsArray | String
appendArray | String
toStringBooleanfalse

noop()

A no-operation function

parseCurrency(value, dec) => Number

Parses value to currency

ParamTypeDefault
valueNumber | String
decString.

parsePhone(value) => String

Parses an irregular value to a phone number

ParamType
valueString

percentile(value, percentile) => Number

Gets the percentile of a number array

ParamTypeDescription
valueArray.<Number>Cannot be empty
percentileNumber0..100

promisify(func) => function

Turns a callback function into a promise

Returns: function - Will now return a promise instead of using callbacks

ParamType
funcfunction

promisifyAll(obj) => Object

Iterates over an Object and creates a copy with promisified functions, non-function and functions ending in Sync will be skipped

ParamType
objObject

pushCap(value, max, item) => Number

Pushes to a capped collection

ParamType
valueArray
maxNumber
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

ParamTypeDefaultDescription
funcfunction
limitNumber1>= 1

random(min, max) => Number

Generate a random number between and including min and max

ParamTypeDescription
minNumber< max
maxNumber> min

randomBlock(len, dict) => String

Generate a random block of characters

ParamTypeDescription
lenNumber>= 0
dictStringCan 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

ParamTypeDefaultDescription
minNumber< max
maxNumber> min
incNumber1> 0

reduce(value, reverse, iter, initial) => *

Iterates over an array or object to create a single value

ParamTypeDefaultDescription
valueArray | Object
reverseBooleanfalse
iterfunction(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

ParamTypeDefaultDescription
valueArray | Object
reverseBooleanfalse
iterfunction(res, key, val, idx) => Promise
initial*0

repeat(value, len) => String

Repeats value len amount of times

ParamTypeDescription
value*
lenNumber>= 0

replace(value, regex, text=) => String

Replaces regex matches of value with text

ParamType
valueString
regexRegExp | String
text=String

sample(value, len) => *

Shuffles and returns len items

Returns: * - Will return a single item if len is 1, otherwise an Array

ParamTypeDefaultDescription
valueArray
lenNumber1>= 1

set(obj, ns, value) => *

Sets a property in an object using a namespace

ParamType
objObject
nsArray | String
value*

setIntervalAndRun(func, interval)

Creates an interval and runs the function immediately

ParamType
funcfunction
intervalNumber

shuffle(value) => Array

Shuffles an array

ParamType
valueArray

size(value, lastIndex) => Number

Gets the length of an array or object

ParamTypeDescription
valueArray | Object
lastIndexBooleanDenotes 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

ParamTypeDescription
valueArray | String
idxNumberIndex to start, if negative, will start at the end
lenNumberLength 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

ParamType
valueString

sort(value, reverse, by) => Array

Sorts an array by a single or array of keys

ParamTypeDefaultDescription
valueArray
reverseBooleanfalse
byArray | 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

ParamTypeDescription
valueString
by=StringCan provide an enums SPACE, COMMA and LINE or a custom join string

spread(value, len, run) => Array

Generates a spread array using value

ParamTypeDefaultDescription
value*
lenNumber>= 0
runBooleanisFunction(value)Will run value before using it

startsWith(value, option) => Boolean

Determines if value starts with option

ParamType
valueString
optionString

sum(value) => Number

Reduce an array by adding the values

ParamTypeDescription
valueArray.<Number>Cannot be empty

template(value, scope) => String

Templates out value using variables declared in the scope object

ParamType
valueString
scopeObject

throttle(func, time, debounce) => function

Throttles or debounces a function

ParamTypeDefaultDescription
funcfunction
timeNumber>= 0
debounceBooleanfalseIn 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

ParamTypeDefault
dateDate | Number | StringDate.now()

timeout(promise, time) => Promise

Creates a timeout for a promise

ParamTypeDescription
promisePromise
timeNumber>= 0

timer() => function

Creates a running timer

Returns: function - () => Number, returns the duration

toArray(value) => Array

Ensures value is an array, slices arguments

ParamType
value*

toBool(value) => Boolean

Converts value to a boolean

ParamType
value*

toDate(value, fromUnix) => Date

Converts value to a date

ParamTypeDefaultDescription
value*
fromUnixBooleanfalseDenotes if the value is UNIX, which requires a millisecond conversion

toLower(value) => String

Converts value to lowercase

ParamType
valueString

toNumber(value, dec) => Number

Converts value to a number

ParamTypeDefault
value*
decString.

toString(value) => String

Converts value to a string

ParamType
value*

toUnix(value) => Number

Converts value to a UNIX timestamp

ParamType
valueDate | Number | String

toUpper(value) => String

Converts value to uppercase

ParamType
valueString

traverseObj(obj, ns, isSet, value) => *

Traverses an object using a namespace and get/set's the corresponding key

ParamTypeDefault
objObject
nsArray | String
isSetBooleanfalse
value*

trim(value, regex) => String

Trims value of whitespace or regex

ParamType
valueString
regexRegExp

trimInner(value) => String

Trims and consolidates all whitespace in value

ParamType
valueString

trunc(value, len, ellipsis) => String

Truncates value at len

ParamTypeDefaultDescription
valueString
lenNumber>= 0
ellipsisString...

unescape(value) => String

Reverses an escaped string

ParamType
valueString

unique(value, iter) => Array

Ensures all mapped values are unique, eliminating duplicates

ParamTypeDescription
valueArray
iterfunction | String(key, idx) => Boolean

values(value) => Array

Returns an array of object values

ParamType
valueObject

verbose(msg, meta)

Verbose logger

ParamType
msgString
metaError

wait(time) => Promise

A simple timeout using await

ParamTypeDescription
timeNumber>= 0

waitUntil(func, args) => Promise

Waits until func returns true

ParamTypeDefaultDescription
funcfunction() => Boolean, Will be rerun every args.interval, if returns true, will exit the wait
argsObject
args.intervalNumber1000>= 0
args.timeoutNumber60000>= 0

warn(msg, meta)

Warn logger

ParamType
msgString
metaError

words(value) => Array.<String>

Converts a string into an array of words

ParamType
valueString
0.3.1

6 years ago

0.3.0

7 years ago

0.2.0

7 years ago

0.1.2

7 years ago

0.1.1

7 years ago

0.1.0

7 years ago