Metarhia Common Library
$ npm install @metarhia/common
Returns: <Array>
tuple with two parts of the array
Split array into two parts
arr
: <Array>
Returns: <Array>
Shuffle an array
arr
: <Array>
Returns: <any>
Random element from array
Returns: <Array>
Generate int array from given range
Example:
range(1, 5);
Result:
[1, 2, 3, 4, 5];
Returns: <Array>
Generate int array from sequence syntax
Example:
list: sequence([81, 82, 83]);
Result:
[81, 82, 83];
Example:
range from..to: sequence([81,,83]) = [81, 82, 83];
Result:
[81, 82, 83];
Example:
range from..count: sequence([81, [3]]) = [81, 82, 83];
Result:
[81, 82, 83];
Example:
range from..max-to: sequence([81, [-2]], 5) = [81, 82, 83];
Result:
[81, 82, 83];
arr
: <Array>
Returns: <any>
element
Get last element of array
Returns: <number>
new value of arr.length
Push single value multiple times
login
: <string>
login to testrequired
: <Array>
required tests configsoptional
: <Array>
optional tests configs, defalult: []
Returns: <AuthenticationStrength>
Function that tests the login
password
: <string>
password to testrequired
: <Array>
required tests configsoptional
: <Array>
optional tests configs, default: []
Returns: <AuthenticationStrength>
Function that tests the password
login
: <string>
login to testpassword
: <string>
password to testrequired
: <Array>
required tests configsoptional
: <Array>
optional tests configs, default: []
Returns: <AuthenticationStrength>
Function that tests the login with password
Returns: <Cache>
Create Cache, enhanced Map
key
: <string>
keyval
: <any>
associated valueAdd key-value pair to cache
prefix
: <string>
to compare with beginning of the keyfn
: <Function>
(optional)
key
: <string>
keyval
: <any>
associative value to be called on each keyClear cache elements that start with prefix
key
: <string>
keyDelete cache element
Returns: <boolean>
always false
Empty function
Returns: <boolean>
always true
Empty function
Empty function
callback
: <Function>
callback to be called with (null)Empty asynchronous callback-last single-argument function
empty
: <any>
incoming value to be ignoredcallback
: <Function>
callback to be called with (null, null)Empty asynchronous callback-last double-argument function
fn
: <Function>
(optional)Returns: <Function>
function(…args) wrapped callback
args
: <Array>
Wrap function: call once, not null
args
: <Array>
argumentsReturns: <Function>
|<null>
callback if any
Extract callback function
It’s unsafe: may return null, allows multiple calls
args
: <Array>
argumentsReturns: <Function>
callback or common.emptiness if there is no
callback
Extract callback
args
: <Array>
argumentsReturns: <Function>
extracted callback
Extract callback
Throws: <TypeError>
if there is no callback
args
: <Array>
argumentsReturns: <Function>
callback or common.emptiness if there is no
callback
Extract callback and make it safe
Wrap callback with once()
fn
: <Function>
Returns: <Function>
function or common.emptiness
if fn is not
a function
Check function and make it safe
fn
: <Function>
Returns: <Function>
|<null>
function or null if fn is
not a function
Check function
x
: <any>
incoming value which will be returnedReturns: <any>
incoming value
Identity function
x
: <any>
incoming value which will be returned into the callbackcallback
: <Function>
callback to be called with first argument
err
: <null>
data
: <any>
Async identity function
value
: <any>
Returns: <boolean>
Check if value is scalar
ds
: <Object[]>
source dataset to be copiedReturns: <Object[]>
Copy dataset (copy objects to new array)
Clone object or array
Duplicate object or array (properly handles prototype and circular links)
Returns: <any>
value
Read property by dot-separated path
Set property by dot-separated path
Returns: <boolean>
Delete property by dot-separated path
args
: <Array[]>
arrays with elements to be mergedReturns: <Array>
Distinctly merge multiple arrays
merger
: <Function>
key
: <string>
current merging key...values
: <any[]>
values under keyobjs
: <Object[]>
objects to be mergedReturns: <Object>
Merge multiple objects with merger
<Symbol>
Not an Enumfrom
: <EventEmitter>
to listen for eventto
: <EventEmitter>
to emit event onevents
: <string>
|<Object>
|<string[]>
Forward events from one EventEmitter to another
Example:
forwardEvents(from, to);
Example:
forwardEvents(from, to, 'eventName');
Example:
forwardEvents(from, to, { eventName: 'newEventName' });
Example:
forwardEvents(from, to, ['eventName1', 'eventName2']);
Returns: <EventEmitter>
Create EnhancedEmitter, enhanced EventEmitter
with wildcard and forward method
args
: <Array>
arguments to be passedCall listener with provided arguments
to
: <EventEmitter>
to emit event onevents
: <string>
|<Object>
|<string[]>
Forward events from one EventEmitter to another
fn
: <Function>
args
: <Array>
arguments to be appliedReturns: <Function>
function(…rest)
rest
: <Array>
argumentsPartially apply arguments to function
mapFn
: <Function>
to apply to every field valueobj
: <Object>
which fields used for mappingReturns: <Object>
with same reference but with transformed fields
Map object fields with provided function
fns
: <Array>
functions to be composedReturns: <Function>
function(…args), composed
args
: <Array>
arguments to be passed to the first functionCompose multiple functions into one
fn
: <Function>
defVal
: <any>
default valuevalue
: <any>
(optional), valueReturns: <any>
result of fn
or defVal
Apply given function to value or default value
arrays
: <Array[]>
arrays to be zippedReturns: <Array>
length is minimal of input arrays length, element
with index i of resulting array is array with elements with index i from input
array
Zip several arrays into one
count
: <number>
new array lengthelem
: <any>
value to replicateReturns: <Array>
replicated
Create array of replicated values
fn
: <Function>
for zipping elements with index iarrays
: <Array[]>
arrays to be zippedReturns: <Array>
zipped, element with index i of resulting array is
result of fn called with arguments from arrays
Zip arrays using specific function
condition
: <Function>
returns: <boolean>
fn
: <Function>
to be curriedargs
: <Array>
arguments for fnReturns: <Function>
function(…args), curried
args
: <Array>
argumentsCurry function until the condition is met
fn
: <Function>
to be curriedcount
: <number>
of times function should be curriedargs
: <Array>
arguments for first curryingReturns: <Function>
curried given times count
Curry fn count times, first curry uses args for first currying
fn
: <Function>
to be curriedReturns: <Function>
to pass arguments that returns curried fn
Curry function curry with fn
fn
: <Function>
to be curriedparam
: <Array>
arguments to the functionReturns: <Function>
function(…args), curried
Curry function with given arguments
args
: <Array>
arguments to save in closureReturns: <Function>
returns: <any>
, result of fn(...args)
fn
: <Function>
to be applied saved argumentsApply arguments
fn
: <Function>
to be calledReturns: <Function>
function(…args), returns: <any>
, result
of fn(arg)
, where arg
- first valid element of args
args
: <Array>
arguments to iterateGet first not errored result of fn
Throws: <Error>
if fn
throws it
fn
: <Function>
function(args, …namedArgs, callback)
args
: <Array>
rest of spreadArgs created by excluding namedArgsnamedArgs
: <Array>
first values of spreadArgs, length is basedcallback
: <Function>
callback, last argument of spreadArgsReturns: <Function>
function(…spreadArgs)
spreadArgs
: <Array>
arguments to be addedRest left, transform function
path
: <string>
path to a file or directory to be removedcallback
: <Function>
callbackRecursively remove directory
path
: <string>
path to a file or directory to be removedReturns: <Promise>
Recursively remove directory
Returns: <string>
key
Generate random key
Returns: <string>
GUID
Generate an RFC4122-compliant GUID (UUID v4)
Returns: <string>
token
Generate random Token
Returns: <string>
crc
Calculate Token crc
Returns: <boolean>
Validate Token
Returns: <string>
hash
Calculate hash with salt
Returns: <boolean>
Validate hash
Returns: <string[]>
[folder1, folder2, code]
Generate file storage key
id
: <number>
Returns: <Array>
minimal length is 2 which contains hex strings
with length of 4
Convert id to array of hex strings
id
: <number>
Returns: <string>
Convert id to file path
path
: <string>
Returns: <number>
Convert file path to id
arr
: <Array>
array-like object to create indices fromReturns: <Iterator>
Create iterator over indices of an array
Returns: <Iterator>
Create iterator iterating over the range
iterators
: <Array>
Returns: <Iterator>
Create iterator by zipping multiple provided iterators into one
fn
: <Function>
this
: <Iterator>
Returns: the result of fn(this)
call.
Call a function with this
. Will be equivalent to calling fn(it)
.
fn
: <Function>
this
: <Iterator>
Returns: <Iterator>
result of fn(this)
wrapped in an Iterator.
Call a function with this
and wrap the result in an Iterator.
Example:
iter([1, 2])
.chainApply(([a, b]) => [a + b, a - b])
.join(', ');
Result:
'3, -1';
mapper
: <Function>
function that maps values and returnsfilterValue
that will be ignored.
value
: <any>
iterator elementthisArg
: <any>
value to be used as this
when calling mapper
filterValue
: <any>
value to filter out mapper
results.Creates an iterator that both filters and maps with the passed mapper
.
This iterator will call mapper
on each element and if mapper returns NOT
filterValue
it will be returned, otherwise it is ignored.
comparator
: <Function>
returns true
if new value should becurrValue
: <any>
current value, starts with undefinednextValue
: <any>
next value<boolean>
true
if next value should be acceptedaccessor
: <Function>
gets value to compare by, currentvalue
: <any>
current iterator value<any>
value to compare bythisArg
: <any>
value to be used as this
when calling accessor
andcomparator
Returns: last iterator value where comparator
returned true
,
<undefined>
by default
Find value in this iterator by comparing every value with
the found one using comparator
defaultValue
: <any>
value to return if this iterator doesn’t have<defaultValue>
Finds first non-nullable value in this iterator
classifier
: <Function>
gets value to group by
value
: <any>
current iterator value<any>
value to group bythisArg
: <any>
value to be used as this
when calling classifier
<Map>
map with arrays of iterator values grouped by keysclassifier
Consumes an iterator grouping values by keys
defaultValue
: <any>
value to be used if iterator is emptyReturns: <any>
|<undefined>
last value of this iterator or
<undefined>
Consumes an iterator returning last iterator value
accessor
: <Function>
gets value to compare by, currentvalue
: <any>
current iterator value<any>
value to compare bythisArg
: <any>
value to be used as this
when calling accessor
Returns: element with maximum value or <undefined>
if iterator
is empty
Find the maximum value in this iterator
accessor
: <Function>
gets value to compare by, currentvalue
: <any>
current iterator value<any>
value to compare bythisArg
: <any>
value to be used as this
when calling accessor
Returns: element with minimum value or <undefined>
if iterator
is empty
Find the minimum value in this iterator
predicate
: <Function>
function returns a value to partitionthisArg
: <any>
value to be used as this
when calling predicate
<Array>
array of partitions (arrays), will always haveConsumes an iterator, partitioning it into Arrays
Transforms an iterator of key-value pairs into an object.
This is similar to what Object.fromEntries()
would
offer.
bufSize
: <number>
size in bytes of the buffer to preallocatevalueSize
: <number>
size in bytes of the produced chunksCreate prefetcher to use when crypto.randomBytes is required to generate
multiple same-size values. bufSize
must be a multiple of valueSize
for this
to work.
Returns: <number>
Generate random integer value in given range
Returns: <number>
Generate random number in the range from 0 inclusive up to
but not including 1 (same as Math.random), using crypto-secure number generator.
iface
: <Object>
to be introspectedReturns: <string[]>
method names
List method names
iface
: <Object>
to be introspectedReturns: <string[]>
property names
List property names
ip
: <string>
(optional), default: ‘127.0.0.1’, IP addressReturns: <number>
Convert IP string to number
Returns: <string[]>
Get local network interfaces
host
: <string>
host or empty string, may contain :port
Returns: <string>
host without port but not empty
Parse host string
obj
: <Object>
containing method to overridefn
: <Function>
name will be used to find methodOverride method: save old to fn.inherited
Previous function will be accessible by obj.fnName.inherited
Mixin for ES6 classes without overriding existing methods
priority
: <string[]>
with prioritys1
: <string>
to compares2
: <string>
to compareReturns: <number>
Compare for array.sort with priority
Example:
files.sort(common.sortComparePriority);
Returns: <number>
Compare for array.sort, directories first
Example:
files.sort(sortCompareDirectories);
Returns: <number>
Compare for array.sort
Example:
files.sort(sortCompareByName);
sizeLimit
: <number>
|<string>
limit of the internalcommon.bytesToSize()
. Defaults to 8 MBReturns: <Promise>
Return a Promise that will be resolved with all the written data once it
becomes available.
tpl
: <string>
template bodydata
: <Object>
hash, data structure to visualizedataPath
: <string>
current position in data structureescapeHtml
: <boolean>
escape html special characters if trueReturns: <string>
Substitute variables
content
: <string>
to escapeReturns: <string>
Escape html characters
Example:
htmlEscape('5>=5') = '5<=5';
fileName
: <string>
file nameReturns: <string>
Extract file extension in lower case without dot
Example:
fileExt('/dir/file.txt');
Result:
'txt';
fileName
: <string>
file nameReturns: <string>
Remove file extension from file name
Example:
fileExt('file.txt');
Result:
'file';
name
: <string>
Returns: <string>
Convert spinal case to camel case
s
: <string>
Returns: <string>
Escape regular expression control characters
Example:
escapeRegExp('/path/to/res?search=this.that');
s
: <string>
Returns: <RegExp>
Generate escaped regular expression
s
: <string>
Returns: <string>
Add trailing slash at the end if there isn’t one
s
: <string>
Returns: <string>
Remove trailing slash from string
filePath
: <string>
Returns: <string>
Get directory name with trailing slash from path
s
: <string>
Returns: <string>
Capitalize string
Returns: <string>
Extract substring between prefix and suffix
s
: <string>
possibly starts with BOMReturns: <string>
Remove UTF-8 BOM
items
: <string[]>
Returns: <RegExp>
Generate RegExp from array with ‘*’ wildcards
Example:
['/css/*', '/index.html'];
Returns: <string[]>
Split string by the first occurrence of separator
Example:
rsection('All you need is JavaScript', 'is');
Result:
['All you need ', ' JavaScript'];
Returns: <string[]>
Split string by the last occurrence of separator
Example:
rsection('All you need is JavaScript', 'a');
Result:
['All you need is Jav', 'Script'];
s
: <string>
separator
: <string>
(optional), default: ‘,’limit
: <number>
(optional), default: -1
, max length of resultReturns: <string[]>
Split string by multiple occurrence of separator
Example:
split('a,b,c,d');
Result:
['a', 'b', 'c', 'd'];
Example:
split('a,b,c,d', ',', 2);
Result:
['a', 'b'];
s
: <string>
separator
: <string>
(optional), default: ‘,’limit
: <number>
(optional), default: -1
, max length of resultReturns: <string[]>
Split string by multiple occurrences of separator
Example:
split('a,b,c,d', ',', 2);
Result:
['c', 'd'];
email
: <string>
email address to normalizeReturns: <string>
normalized email address
Normalize email address according to OWASP recommendations
Returns: <boolean>
Compare time1 and time2
Example:
isTimeEqual(sinceTime, buffer.stats.mtime);
date
: <Date>
(optional), default: new Date()
Returns: <string>
Get current date in YYYY-MM-DD format
date
: <Date>
(optional), default: new Date()
Returns: <string>
Get current date in YYYY-MM-DD hh:mm format
s
: <string>
duration syntaxReturns: <number>
milliseconds
Parse duration to seconds
Example:
duration('1d 10h 7m 13s');
n
: <number>
durationReturns: <string>
Convert integer duration to string
bytes
: <number>
sizeReturns: <string>
Convert integer to string, representing data size in Kb, Mb, Gb, and Tb
size
: <string>
sizeReturns: <number>
Convert string with data size to integer
fn
: <Function>
Returns: <Function>
function(…args), wrapped with try/catch
interception
args
: <Array>
arguments to be passed to wrapped functionMake function raise-safe
depth
: <number>
|<RegExp>
initial stack slice orstack
: <string>
stack string, optionalTry to detect the filepath of a caller of this function.
See github for full contributors list