Simple javascript, lodash alternative library, for support contact me at eaglex.net
- Version:
- ^2.x.x
- License:
- MIT Eaglex
- Source:
Methods
(inner) alert(…args)
Extends console.log with [alert] prefix
- produces yellow color output
- this method does not work on window object ( for obvious reasons! )
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
any
|
<repeatable> |
(inner) arraySize(arr) → {number}
Test item is an array, and check the size
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
Returns:
- Type:
-
number
Example
arraySize([1,2,3]) // 3
arraySize({a:1}) // 0
(inner) arrayWith(arr, prop) → {array}
Mixed array of objects and values, grab items[] that include specific prop
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
mixed [{a:true},...] |
prop |
string
|
Returns:
- Type:
-
array
items that include specific prop
Example
arrayWith([ [], { a: undefined }, { b: 3 }, { a: 1 } ], 'a')
// [ { a: undefined }, { a: 1 }]
arrayWith([ { a: 1 } , 1,[], undefined, { b: 3 } ], 'b')
// [ { b: 3 }]
(inner) asJson(data) → {string}
Provided data is returned in pretty json
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
data |
any
|
array/object |
Returns:
- Type:
-
string
JSON.stringify(o , null, 2)
Example
asJson( { a:{ b: { c:'hello world' } } } )
// returns:
{
"a": {
"b": {
"c": "hello world"
}
}
}
(inner) attention(…args)
Extends console.log with [attention] prefix
- produces blue color output
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
any
|
<repeatable> |
(inner) cancelPromise(config) → {Promise}
Cancelable synchronous process, determines how long to wait before we exit
- If the promise never resolves or takes too long, we can cancel when maxWait expires
- Source:
Parameters:
| Name | Type | Description | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
config |
object
|
|
Returns:
- Type:
-
Promise
the promise provided in config.defer, dont need to use it
Example
let dfr = sq()
cancelPromise({ defer:dfr, // can use standard Promise, sq(), or node.js q.defer
checkEvery: 200, // << log process on every
maxWait: 3000, // expire promise
message: 'waited too long', // << use this error message
logging: true, // display process
id: new Date().getTime(), // custom id to display or on error
cbErr: function({ error, defer, id }) {
// update our reject message
defer.reject(error)
}
}) // returns promise
// will catch the timeout rejection
df2.promise.catch(onerror)
// or would exist waiting process and resolve
// dfr.resolve('success')
// dfr.promise.then(log)
(inner) checkLoggerSetting(logType) → {'on'|'off'}
Internal method check if any log,warn,error,onerror are currently disabled
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
logType |
logType
|
Returns:
- Type:
-
'on'|'off'
(inner) chunks(arr, size) → {array}
Split array to chunks by providing size number
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
arr |
array
|
required |
|
size |
number
|
0 |
how many chunks per batch |
Returns:
- Type:
-
array
chunked array by size
Example
chunks( [1,2,3,4,5,6] , 2) // [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
(inner) copy(data) → {any}
Makes item copy
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
data |
any
|
Returns:
- Type:
-
any
copy of the same input type, or primitiveValue type if class or method supplied
Example
copy({ a: 1, b:function(){} }) //=> {a:1}
copy([1,2,3]) //=> / [1,2,3]
copy( function(){}) //=> Function: anonymous
copy(null) //=> null
copy(true) //=> true
(inner) copyBy(obj, refs) → {object}
Copy object by property name
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
object
|
|
refs |
array
|
supply list of keys |
Returns:
- Type:
-
object
new object of copied values
Example
copyBy({ a: 1, b: 2, c: 3 }, ['a', 'c']) // {a: 1, c: 3}
copyBy({ a: 1, b: 2, c: 3 }) // {}
copyBy({}) } // {}
(inner) copyDeep(data) → {any}
For complex arrays of objects: [{...},{...}]
- will copy each array item separately and check for Object>object then make copy
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
data |
any
|
object or array |
Returns:
- Type:
-
any
copy of the same input type, or primitiveValue type where method supplied
Example
copyDeep({ a: {b:{c:{}}} }) //=> { a: {b:{c:{}}} })
copyDeep([{ a: (new function(){this.b=1}()) }]) //=> [ { a: {b:1} } ]
copyDeep({ a: (new function(){this.b=1}()) }) //=> { a: { b:1 } }
(inner) debug(…args)
Extends console.log with [debug] prefix
- produces green color output
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
any
|
<repeatable> |
(inner) delay(time) → {Promise}
Delay a sync/async process, to be executed after delay is resolved
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
time |
number
|
0 |
in ms |
Returns:
- Type:
-
Promise
always resolves
Example
// async
log('delay start')
await delay(2000)
// continue with process
// sync
delay(2000).then(()=>{...})
(inner) disableLogging() → {true|false}
If you used logging in your application from the moment this method was called all logging will be disabled
- it affects: log, warn,error, onerror, errorTrace, stack, attention, alert, debug
- Source:
Returns:
- Type:
-
true|false
(inner) dispatcher(uid, debug) → {Dispatcher}
Lightweight Event Dispatcher, allowing dispatch anywhere in code, very handy in callback/hell situations, deep promises, or other computations. Integrated with callback memory so you dont have to subscribe first to get your data.
- Call next before subscribe
- Avoid ugly callback > callback > callback hell!
- Avoid messy Promises
- Prefer clean, readable code hierarchy
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
uid |
string
|
number
|
(optional) or generated |
|
debug |
boolean
|
false |
for extra debug messages |
Returns:
- Type:
-
Dispatcher
Example
const ds = dispatcher()
ds.next({ data: 'hello world' })
ds.subscribe(function (data, uid, index) {
log('on subscribe', data, uid, index)
// this.delete() // delete dispatcher
}).onComplete(uid => {
// last call on deletion
})
ds.next({ data: 'hello again' })
ds.delete() // delete dispatcher
ds.next({ data: 'another' }) // never called
(inner) dupes(item, index) → {array}
Duplicate item x:number of times
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
item |
any
|
||
index |
number
|
0 |
times to duplicate the item |
Returns:
- Type:
-
array
same item duplicated
Example
dupes('any', 2)
// ['any','any']
dupes([{a:1},{b:1}], 2)
// [ [{a:1},{b:1}], [{a:1},{b:1}] ]
(inner) errorTrace(data, asArray)
Extended console.error, stack trace
- produces/prefixed [ERROR]: ...
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
data |
any
|
optional |
|
asArray |
boolean
|
false |
if set, will output stack trace as array, otherwise a string |
Example
errorTrace('error data', true) // returns [[ERROR],... including full stack trace
(inner) exFromArray(arr, excludes) → {array}
Array including any objects and values
- Exclude items from array matchd by
excludes[], and replace with undefined keeping index position
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
mixed with objects to exclude by propName |
excludes |
Array.<string>
|
propNames to match each object in arr[x] |
Returns:
- Type:
-
array
mixed with any other types as per input, in same index position
Example
exFromArray([{ a: 1, c: 5 }, { a: 10 }, { b: 2 }, { c: 1, a: 2 }], ['a', 'b'])
// [ { c: 5 }, undefined, undefined, { c: 1 }]
exFromArray([ null,1,{ a: 1, c: 5 }, { a: 10 }, { b: 2 }, { c: 1, a: 2 },'2'], ['a', 'c'])
// [null,1, undefined,undefined,{ b: 2 },undefined,'2']
(inner) exactKeyMatch(object, source, cbEval) → {boolean}
Test if ALL keys match between object{} and source{}
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
object |
object
|
|
source |
object
|
|
cbEval |
function
|
undefined
|
(optional) operator, continue checking when callback returns !!true |
Returns:
- Type:
-
boolean
when ALL keys found between 2 objects, return true
Example
exactKeyMatch({ a: 2, b: 1, c: 2 }, { c: 1, a: 1, b: 1 }) //=> true
exactKeyMatch({ a: 2, b: 1 }, { c: 1, a: 1, b: 1 }) //=> false
exactKeyMatch({}, { c: 1, d: 1}) //=> false
exactKeyMatch({ a: 2, b: 1, c: 2 }, { c: 1, a: 1, b: 1 }, ()=> 1+1===3)
//=> false, because callback return !!false
(inner) flatten(arr) → {array}
Flatten 2 level array to 1 level: [[]] > [], [[[]]] > [[]]
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
Returns:
- Type:
-
array
Example
flatten([['hello world']]) // ['hello world']
(inner) flattenDeep(arr) → {array}
Flatten all array levels to 1, example: [[['hello']]] > ['hello']
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
Returns:
- Type:
-
array
Example
flattenDeep([[[['hello world']]]) // ['hello world']
(inner) hasProto(el, cbEval) → {boolean}
Check if item has access to proto
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
el |
any
|
|
cbEval |
function
|
undefined
|
optional callback, continue checking when callback returns !!true |
Returns:
- Type:
-
boolean
Example
hasProto({}) // true
hasProto('') // true
hasProto(-1) // true
hasProto(false) // true
hasProto(undefined) // false
hasProto(null) // false
hasProto(NaN) // true
hasProto({}, ()=> Object.keys({}).length ) // false because object has no keys
(inner) head(arr) → {any}
Get first item from array
- Allow 1 level [[1,2]]
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
Returns:
- Type:
-
any
first array[] item[0]
Example
head([[{ value: 1 }, { value: 2 }]]) // { value: 1 }
head([[ [1], {value:1} ]]) // [1]
head([1,2]) // 1
(inner) inIndex(str, patterns) → {number}
Test accuracy of a match[x] in a string
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string
|
to match against |
patterns |
Array.<RegExp>
|
RegExp patterns to test against |
Returns:
- Type:
-
number
size of index patterns that matched in the string
Example
inIndex('ab cd eFG', [/fg/i, /\sCD\s/i, /ab/]) // 3 < found in three pattern arrays
inIndex('abcdeFG', [/%fg/i, /1CD/i, /ab/]) // 1 (last)
(inner) includes(id, matchArr) → {boolean}
Compare match array items with the id, if any were found return true
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
id |
any
|
single item represented in mach array |
matchArr |
Array.<number>
|
array of item type that we can match by id |
Returns:
- Type:
-
boolean
when id was found in matchArr
Example
includes(1, [2,'0',false,1]) // true
includes('5', [2,'5',false,1]) // true
(inner) interval(cb, every, endTime)
Execute callback every interval, then exit on endTime
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
cb |
intervalCB
|
||
every |
number
|
0 | |
endTime |
number
|
0 |
Example
interval(() => log('interval called'), 100, 300)
(inner) isArray(arr, cbEval) → {true|false}
Check item is an array
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
any
|
|
cbEval |
function
|
undefined
|
(optional) callback operator, continue checking when callback returns !!true |
Returns:
- Type:
-
true|false
Example
isArray([]) // true
isArray({}) // false
isArray(new Array()) // true
isArray(new Array(), ()=>[1,2].length===1) // false, because callback return !!false
isArray({}, ()=>true) // false // not array
(inner) isBigInt(n) → {true|false}
Test provided item is BigInt
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
n |
any
|
Returns:
- Type:
-
true|false
Example
isBigInt( BigInt(Number.MAX_SAFE_INTEGER) ) // true
isBigInt( 1n ) // true
isBigInt( (2n ** 54n) ) // true
(inner) isBoolean(el) → {true|false}
Check if item is a boolean
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
el |
any
|
Returns:
- Type:
-
true|false
Example
isBoolean(null) // false
isBoolean(undefined) // false
isBoolean(false) // true
isBoolean(new Boolean(false)) // true
(inner) isClass(obj, cbEval) → {true|false}
Test item is a class{} constractor, that can be initiated
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
any
|
|
cbEval |
*
|
(optional) callback operator, continue checking when callback returns !!true |
Returns:
- Type:
-
true|false
Example
isClass(Array) // true
isClass(Object) //true
isClass((class {}) ) //true
// instance of a class
isClass( (new function() {}()) ) // false
isClass( new Object() ) // false
(inner) isEmpty(value) → {boolean}
Check item has some value, set of props, or length
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
value |
any
|
any |
Returns:
- Type:
-
boolean
Example
isEmpty({}) // true
isEmpty({a:1}) // false
isEmpty([]) // true
isEmpty([0]) // false
isEmpty(1) // false
isEmpty(false) // true
(inner) isError(el) → {true|false}
Check item is of Error object family
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
el |
any
|
Returns:
- Type:
-
true|false
Example
isError(Error()) // true
isError(new Error()) // true
isError(true) // false
isError(xError()) // true
isError(referenceError()) // true
(inner) isFalse(el) → {true|false}
Check if item is lt < 1, false, null or undefined
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
el |
any
|
number/boolean |
Returns:
- Type:
-
true|false
Example
isFalse(undefined) // false
isFalse(5) // false
isFalse(0) // true
isFalse(-1) // true
isFalse(true) // false
isFalse(false) // true
isFalse({}) // false
isFalse( new Boolean(false) ) // true
(inner) isFalsy(el) → {boolean}
Check if any item type is falsy, object, array, class/instance, having no props set
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
el |
any
|
Returns:
- Type:
-
boolean
Example
isFalsy({}) // true
isFalsy({a:1}) // false
isFalsy([]) // true
isFalsy([1]) // false
isFalsy(true) // false
isFalsy(false) // true
isFalsy(0) // true
isFalsy( (new function(){}()) ) // true
isFalsy( (new function(){this.a=false}()) ) // false
(inner) isFunction(el) → {true|false}
Check if item is a function
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
el |
any
|
Returns:
- Type:
-
true|false
Example
isFunction(()=>{}) // true
isFunction(Function) // true
(inner) isInstance(obj, cbEval) → {boolean}
Testing if item{} is a new Item{}, instance of a class
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
any
|
|
cbEval |
function
|
undefined
|
(optional) continue checking when callback returns !!true |
Returns:
- Type:
-
boolean
Example
isInstance({}) // false
isInstance(new function(){}) // true
isInstance(new class(){} ) // true
isInstance(function () { }) // false
isInstance([]) // false
(inner) isNull(el) → {true|false}
Check if item is ===null
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
el |
any
|
Returns:
- Type:
-
true|false
Example
isNull(null) // true
isNull(undefined) // false
(inner) isNumber(n) → {true|false}
Check item is a number
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
n |
any
|
Returns:
- Type:
-
true|false
Example
isNumber(-1) // true
isNumber( new Number(-1) ) // true
isNumber(NaN) // true
isNumber(true) // false
isNumber([]) // false
(inner) isObject(obj, cbEval) → {true|false}
Test item is a true object, and not array
- Should not be a function/primitive, or class (except for instance)
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
any
|
|
cbEval |
function
|
undefined
|
(optional) callback operator, continue checking when callback returns !!true |
Returns:
- Type:
-
true|false
Example
isObject({}) // true
isObject([]) // false
isObject( (new function(){}) ) // true
isObject((function () { })) }) // false
isObject((new class { })) // true
isObject( (class{}) ) // false
isObject(new Error()) // true
isObject(null) // false
isObject( {}, ()=>false ) // false, due to callback !!false
isObject( [], ()=>Object.keys({1:1}).length ) // false, not an object
(inner) isPromise(defer) → {true|false}
Check for Promise / q.defer / and xutils promise ( sq() ),
- test if its a resolvable promise
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
defer |
any
|
Returns:
- Type:
-
true|false
Example
isPromise( function () { } ) // false
isPromise( Promise.resolve()) ) // true
isPromise( sq() ) // true
isPromise( q.defer() ) // true
(inner) isQPromise(defer) → {true|false}
There are 2 types of promises available javascript standard Promise and the node.js q.defer() promise
- this method tests for the q.defer node.js promise version
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
defer |
any
|
q.defer() promise to check against |
Returns:
- Type:
-
true|false
Example
isQPromise(Promise.resolve()) }) // false
isQPromise( sq() ) // false
isQPromise( q.defer() ) // true (referring to node.js q )
(inner) isRegExp(expression) → {boolean}
Check pattern is an expression of RegExp
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
expression |
RegExp
|
/\\/ |
Returns:
- Type:
-
boolean
Example
isRegExp('abc') // false
isRegExp(/abc/) // true
(inner) isSQ(defer) → {true|false}
Test if item is our SimpleQ promise
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
defer |
any
|
Returns:
- Type:
-
true|false
Example
isSQ( sq() ) // true
isSQ( Promise.resolve() ) // false
isSQ( q.defer() ) // false
(inner) isString(str, cbEval) → {boolean}
Test item is a string type
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
str |
any
|
|
cbEval |
function
|
undefined
|
(optional) operator, continue checking when callback returns !!true |
Returns:
- Type:
-
boolean
Example
isString('') // true
isString(new String()) // true
isString(NaN) // false
isString(new Date()) // false
isString('123', ()=>'123'.length>5) // false, callback return !!false
isString('123', ()=>'123'.length>2) // true
(inner) isTrue(el) → {true|false}
Check if item is gth > 0, true, basically opposite of isFalse()
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
el |
any
|
number/boolean |
Returns:
- Type:
-
true|false
Example
isTrue(undefined) // false
isTrue(5) // true
isTrue(0) // false
isTrue(-1) // false
isTrue(true) // true
isTrue(false) // false
isTrue([]) // false
isTrue( new Boolean(true) ) // true
(inner) isUndefined(el) → {true|false}
Check if item is ===undefined
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
el |
any
|
Returns:
- Type:
-
true|false
Example
isUndefined(undefined) // true
isUndefined(null) // false
(inner) last(arr) → {any}
Gets last item from array
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
Returns:
- Type:
-
any
Example
last([{},{},[1], { value: 1 }]) // { value: 1 }
(inner) log(…args)
Extends console.log with [log] prefix
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
any
|
<repeatable> |
(inner) loggerSetting(logType, logMode) → {true|false}
Allow enabling and disabling of loggers: log/warn/error/onerror/attention/debug/alert
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
logType |
logType
|
log |
logger name |
logMode |
string
|
off |
off/on |
Returns:
- Type:
-
true|false
Example
loggerSetting('log','off') // future calls to log() will be disabled
// this applies to all logger methods:
(inner) loggingON() → {true|false}
When xUtilsConfig wasn't set, then we are on, else if ..xUtilsConfig==='off', do not print logs
- Source:
Returns:
- Type:
-
true|false
(inner) loop(size, cb) → {array}
Looping each item inside of callback
- Returned cb is pushed to array
- break loop when returning
{break:true}inside callback
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
size |
number
|
0 | |
cb |
loopCB
|
callback issued at end of each loop que |
Returns:
- Type:
-
array
whatever was returned inside the loop
Example
loop(5,inx=>10+inx) // [10, 11, 12, 13, 14]
loop(3,inx=>{
if(inx===3) return {break:true}
return {[inx]:inx+1}
}) // [ { '0': 1 }, { '1': 2 }, { '2': 3 } ]
(inner) matched(str, expression) → {boolean}
Match string value by expression
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
str |
string
|
to match against expression |
|
expression |
RegExp
|
/\\/ |
valid expression /xyz/ |
Returns:
- Type:
-
boolean
Example
matched('aabc', /^abc/)) // false
matched('aaBC', /abc/i) // true
(inner) objectSize(obj) → {number}
Check size object, we want to know how many keys are set
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
object
|
Returns:
- Type:
-
number
number of keys on the object
Example
objectSize({ a: 1, b: 2 }) }) // 2
objectSize([1,2]) // 0
objectSize( (new function(){this.a=1}()) ) // 1
objectSize( (new function(){}()) ) // 0
(inner) onerror(…args)
Extends console.error with [error] prefix
- produces red color output
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
any
|
<repeatable> |
(inner) pickFromArray(arr, picks) → {array}
Array selection tool
- Filter items in
array[item,item]bypicks[Types|primitives,values]conditions - Does not support deep selections from picks[], only 1 level deep, but you can use object types,
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
array of any |
picks |
Array.<any>
|
item in picks tests for all passing conditions, like object types, primitive type, and matching values
|
Returns:
- Type:
-
array
items that passed each pick condition, keeping the same index order
Example
let picks = [Boolean, 'hello', Object, { a: 1 }, BigInt] // only these types/values will be tested
pickFromArray([false, undefined, { a: 1 }, 'hello', ['hello'], {}, 1234567890123456789012345678901234567890n, 'not selected'], picks )
//> [ false,{ a: 1 },'hello',{},1234567890123456789012345678901234567890n ]
let picks = [Number, Boolean] // select only numbers and booleans from array
pickFromArray([undefined, 1, {}, 2, null, [], 'hello world', 3, true, 4, null, 5], picks)
//> [ 1, 2, 3, true, 4, 5 ]
let picks = [undefined, [undefined] ] // select all undefined from array
pickFromArray([undefined, false, 1, true, {}, [1], [undefined], null], picks)
// [undefined, [undefined]]
// we only want to pick items that are {data} objects containing inner objects
let picks = [{ data: Object }]
pickFromArray([{ data: { a: 1 } }, { data: 1 },false, ['hello'], { data: { d: 2 } }, { data: { b: 2 } }, 1, 2, [], {}], picks)
//=> [{ data: { a: 1 } },{ data: { d: 2 } },{ data: { b: 2 } } ]
let picks = [{ a: Object, b: 1 }] // narrowing down the results, should select all array objects that at least contain all the above
pickFromArray([{ a: { a: 1 }, b: 1, c:1 }, { data: 1 }, { a: { a: 1 }, b: 1 }, { data: null }, false, 1, 2, [], {}], picks)
//=> [ { a: { a: 1 }, b: 1, c: 1 }, { a: { a: 1 }, b: 1 }]
(inner) referenceError(opts) → {XReferenceError}
Extended ReferenceError with extra props, native behaviour describe on (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError
- method extends {ReferenceError}
- Source:
Parameters:
| Name | Type | Description | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
opts |
Object
|
|
Returns:
- Type:
-
XReferenceError
extended new ReferenceError(...)
Example
try {
throw referenceError({name:'MyReferenceError',message:'my message',fileName:'example.js' lineNumber:1})
} catch(err){
log(e instanceof ReferenceError) // true
log(e.name) // "MyReferenceError"
log(e.message) // "my message"
log(e.fileName) // "example.js"
log(e.lineNumber) // 1
log(e.stack) // "@Scratchpad/2:2:9\n"
}
(inner) resetLogging() → {true|false}
Change state of xutils loggers when calling at top of hoist level.
- affects: log, warn,error, onerror, errorTrace, stack, attention, alert, debug
- Source:
Returns:
- Type:
-
true|false
Example
resetLogging() // will reset any previously set loggerSetting(...) options
(inner) resolver(fn, timeout, testEvery) → {Promise.<any>}
Run some method that returns value in future, checking updates until timeout, or exit when data becomes available
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
fn |
resolverCB
|
callable method that returns some value |
|
timeout |
number
|
5000 |
(ms) specify max time to wait for data before timeout |
testEvery |
number
|
50 |
how ofter to test data availability |
Returns:
- Type:
-
Promise.<any>
always resolves, when return is empty it will be wrapped in an {error}
Example
resolver(()=>Promise.resolve({data:'hello world'}),5000,50).then(n=>{
log({resolver:n})
})
resolver(()=>Promise.reject('some error'),5000,50).then(n=>{
log({resolver:n}) // {error: 'some error'}
})
(inner) selectiveArray(selectBy, data) → {array}
Select data from array of objects by reference, and go down recursively in order of selectBy ['a.b'] ref
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
selectBy |
Array.<string>
|
list of uniq references, example ['a.b.c.d.e','e.f.g'], each selectBy/item targets nested object props |
data |
Array.<any>
|
list of objects to target by select ref |
Returns:
- Type:
-
array
by selected order in same pair index
Example
// select b from both arrays, return same index order
selectiveArray(['a.b'], [ { a: { b:'hello' }, b:{c:'hello'} },{ a: { b:'world' },b:{c:'world'} } ])
//=> [ [ 'hello'], [ 'world'] ]
//select b, and select c from both arrays, return same index order
selectiveArray(['a.b','b.c'], [ { a: { b:'hello' }, b:{c:'hello'} },{ a: { b:'world' },b:{c:'world'} } ])
//=> [ ['hello','hello'], ['world','world'] ]
// destructuring example :
let [b,c]=Array.from( flatten(selectiveArray(['a.b','b.c'], [ { a: { b:'hello' }, b:{c:'world'} }]) ) ).values()
// b==="hello", c ==="world"
(inner) shuffle(arr) → {array}
Randomise items in array
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
Returns:
- Type:
-
array
(inner) someKeyMatch(object, source, cbEval) → {boolean}
Test if ANY keys match between object{} and source{}
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
object |
object
|
|
source |
object
|
|
cbEval |
function
|
undefined
|
(optional) operator, continue checking when callback returns !!true |
Returns:
- Type:
-
boolean
when at least 1 key is found between 2 objects, return true
Example
someKeyMatch({ a: 2, b: 1, c: 2 }, { d: 1, e: 1, a: 1 })
//=> true , {a} was found
someKeyMatch({ a: 2, b: 1, c: 2 }, { d: 1, e: 1, a: 1 }, ()=>1-1===1)
//=> false, because callback return !!false
(inner) spread(data, props) → {object}
Spread data of an object as you would ...data, but with selected prop names that match the object
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
data |
object
|
must be an object |
props |
Array.<string>
|
prop list matching first level props on an object |
Returns:
- Type:
-
object
Example
spread({a:1,b:2,c:{}},['a','c']) // {a:1,c:{}}
spread({a:1,b:2,c:3},[]) // {}
(inner) spreadWith(arr, indexArr) → {Array.<any>}
Spread only selected array items matching index number
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
Array.<any>
|
|
indexArr |
Array.<number>
|
index number matching array |
Returns:
- Type:
-
Array.<any>
Example
spreadWith(['a','b','c'],[1,2]) // ['b','c']
spreadWith(['a','b','c'],[2,4]) // ['c']
(inner) sq() → {SimpleQ}
SimpleQ / instanceof Promise & SimpleQ
- Deferred simplified promise
- Available methods:
resolve() / reject() / (get) promise / progress( (value:string,time:number)=>self,every?:number,timeout?:number ):self, progress() calls with values:resolved | rejected | in_progress | timeout, its discarted when fulfilled or timedout
- Source:
Example
let defer = sq()
let every = 100 // how often to check
let timeout = 5000 // exists if not already resolved or rejected
defer.progress((val,time)=>{
// val //> "resolved" | "rejected" | "in_progress" | "timeout"
log('[progress]',val,time)
}, every, timeout)
.then(n=>{
log('[sq][resolve]',n)
}).catch(err=>{
onerror('[sq][reject]',err)
})
defer.resolve('hello world')
// defer.reject('kill it')
// or
defer.resolve('hello world')
.then(log)
// or
defer.then(log)
.resolve('hello world')
// or
defer.reject('ups')
.catch(onerror)
// or either
await defer // resolves // rejects?
await defer.promise // resolves // rejects?
(inner) stack(data, asArray)
For stack tracing
- produces/prefixed [STACK TRACE]: ...
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
data |
any
|
||
asArray |
boolean
|
false |
if set, will output stack trace as array, otherwise a string |
(inner) stringSize(str) → {number}
Test the length of string
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string
|
Returns:
- Type:
-
number
length of string
Example
stringSize('abc') // 3
stringSize(-1) // 0
stringSize('-1') // 2
stringSize(undefined) // 0
stringSize([123]) // 0
(inner) timer(cb, time)
Timer callback executes on timeout
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
cb |
timerCB
|
||
time |
number
|
0 |
Example
timer(() => log('timer called'), 2000) // executed after time expired
(inner) trim(str) → {string}
Trim boths sides of string, including new lines, and multiple spaces to single space
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string
|
Returns:
- Type:
-
string
Example
trim(` \n hello
\n
\r
\n
\r
world
`) //> hello world
(inner) trueProp(obj) → {object}
Object with true entities will be returned
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
object
|
required |
Returns:
- Type:
-
object
Example
trueProp({ a: NaN, b: 0, c: false, d: -1, e: NaN, f: [], g: 'hello', h: {}, i: undefined, j:'' })
//=> {g: 'hello'}
(inner) trueVal(arr) → {Array.<any>}
Exclude any falsy values from array, such as: [0,null,false,{},undefined, -1,'',[]]
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
Array.<any>
|
mixed |
Returns:
- Type:
-
Array.<any>
only non falsy items are returned
Example
trueVal([-1, 0,1, {}, "hello", [], { name: 'jack' }, false, null, NaN, undefined,true])
//=> [1,'hello',{ name: 'jack' },true]
(inner) trueValDeep(arr) → {Array.<any>}
Exclude any falsy values from array: [0,null,false,{},undefined, -1,'',[]], but testing 1 level deeper, compared to trueVal()
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
Array.<any>
|
mixed |
Returns:
- Type:
-
Array.<any>
only non falsy items are returned
Example
trueValDeep([1, 0, [], {}, "hello", [0, undefined, -1, false, NaN, 1], { name: 'jack' }, false, null, undefined])
//=> [ 1, 'hello', [ 1 ], { name: 'jack' } ]
(inner) truthFul(obj) → {object}
Return new object excluding all undefined values in top level
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
object
|
Returns:
- Type:
-
object
Example
truthFul({ a: undefined, b: 1, c: {} }) // { b: 1, c: {} }
(inner) typeCheck(el, standard) → {Object}
Examines element for its type, provided value, and primitive value
- Source:
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
el |
any
|
||
standard |
boolean
|
true |
|
Returns:
- Type:
-
Object
{ "type":date,NaN,promise,instance,prototype,array,...typeof, value: number, primitiveValue }
Example
typeCheck({}) // {type:'object', value:0, primitiveValue: Object() }
typeCheck({a:1,b:2}) // {type:'object', value:2, primitiveValue: Object() }
typeCheck([2,3],false) // {type:'array', value:2, primitiveValue: Array() }
typeCheck(Date,false) // {type:'date', value:1, primitiveValue: Date() }
typeCheck(2) // {type:'number', value:2, primitiveValue: Number() }
typeCheck(false) // {type:'boolean', value:0, primitiveValue: Boolean() }
typeCheck(true) // {type:'boolean', value:1, primitiveValue: Boolean() }
typeCheck(null,false) // {type:'null', value:0, primitiveValue: Object() }
typeCheck(null) // {type:'object', value:0, primitiveValue: Object() }
typeCheck(undefined) // {type:'undefined', value:0, primitiveValue: undefined }
typeCheck(function () { }) // {type:'function', value:1, primitiveValue: Function }
typeCheck(Promise.resolve(),false) // {type:'promise', value:1, primitiveValue: Function }
typeCheck(Promise.resolve()) // {type:'object', value:1, primitiveValue: Function }
typeCheck(BigInt(1)) // { type: 'bigint', value: 1, primitiveValue: 0n }
typeCheck( new Error()) // { type: 'object', value: 0, primitiveValue: Error() }
(inner) uniq(arr) → {array}
Returns new array of unique values
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
Returns:
- Type:
-
array
Example
uniq([1, 1, 3, 'a', 'b', 'a', null, null, true, true])
// [1,3,'a','b',null,true]
(inner) uniqBy(arr, propName) → {array}
New array with uniq property values
- Selects first match ignoring others of those which prop values are repeated
- non matching objects, preserved as usual
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
arr |
array
|
mixed array of items and objects |
propName |
string
|
select key and test values, are repeated |
Returns:
- Type:
-
array
[{},...] items with object items whos values are uniq
Example
uniqBy([{ a: 1, b: 2 }, 1, { b: 1 }, 5, { a: 1 }, null, { a: 1, b: 2 }], 'a')
//=> [ { a: 1, b: 2 }, 1, { b: 1 }, 5, null ]
uniqBy([{ c: 1, b: 2 }, { c: 1 }, { c: 1 }, { c: 1, b: 2 }], 'c')
//=> [ { c: 1, b: 2 } ]
uniqBy([{ a: 1, b: 2 }, null, undefined, true, 1, { a: 1 }, { a: 3 }, false], 'a')
//=> [ { a: 1, b: 2 }, null, undefined, true, 1, { a: 3 }, false ] prop[values] are not uniq
(inner) unsubscribe(subscriptionsnullable, messagenullable) → {number}
Unsubscribe from an RX/subscription, by providing an array of active subs
- invalids are silently dismissed and disposed
- source input is finally spliced
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
subscriptions |
Array.<any>
|
<nullable> |
Array of RX subscriptions |
message |
string
|
<nullable> |
optional message displayed when item is unsubscribed |
Returns:
- Type:
-
number
index count of items unsubscribed
Example
unsubscribe([sub1,sub2,sub3],'on component destroyed') // 3
unsubscribe([sub1,'',sub3],'unsubscribed') // 2, but the empty item is also disposed from array
(inner) validDate(dt, cbEval) → {true|false}
Evaluate if data is an actual Date
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
dt |
Date
|
|
cbEval |
function
|
undefined
|
(optional) callback operator, continue checking when callback returns !!true |
Returns:
- Type:
-
true|false
Example
validDate(new Date('')) // false
validDate(new Date()) // true
validDate( new Date(), ()=>false ) // false callback !!false
(inner) validID(id) → {string}
Convert to string, remove spaces, toLowerCase
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
id |
string
|
number
|
Returns:
- Type:
-
string
Example
validID('sdfkj 45 AMKD') // sdfkj45amkd
(inner) warn(…args)
Extends console.log with [warn] prefix
- produces bright color output
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
any
|
<repeatable> |
(inner) withHoc(item, …args) → {function}
High order caller, concept taken from React HOC.
- Promise support, we can provide deferred callback
- if rejectable error is not callable, message is:
DEFERRED_NOT_CALLABLE
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
item |
withHocCB
|
callable function |
|
args |
*
|
<repeatable> |
(optional) any number of arguments (,,,,) that callable function has available |
Returns:
- Type:
-
function
callable function withHoc(...args) OR deferred if a promise
Example
function fn(a = 1, b = 2, c = 3) {
return a + b + c
}
// example 1
let fnHocked = withHoc(fn)
fnHocked() // > 6
// example 2
fnHocked = withHoc(fn, 4, 5, 6) // provided fn() arguments from upper caller
fnHocked() // > 15
// example 3
fnHocked = withHoc(fn, 4, 5, 6)
// above arguments replaced with in final call
fnHocked(7, 8, 9) // > 24
// example 4
fnHocked = withHoc(Promise.resolve(fn), 4, 5, 6)
// above arguments replaced with in final call
fnHocked(7, 8, 9).then(log) // > 24
// example 5
fnHocked = withHoc(Promise.reject(fn), 4, 5, 6)
// above arguments replaced with in final call
fnHocked(7, 8, 9).catch(onerror) // > 24
// example 6 not a deferred caller:
fnHocked = withHoc(Promise.reject('fn'), 4, 5, 6)
// above arguments replaced with in final call
fnHocked(7, 8, 9).catch(onerror) // > DEFERRED_NOT_CALLABLE
(inner) xError(opts) → {XError}
Extended Error(...) with extra {id,name} used to throw exception. Access to available props as describe on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error
- method extends {Error}
- Source:
Parameters:
| Name | Type | Description | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
opts |
Object
|
|
Returns:
- Type:
-
XError
extended new Error(...)
Example
try {
throw xError({ id:123,name: 'MyError', message: 'my message', fileName: 'example.js', lineNumber: 20 })
} catch (e) {
console.log(e instanceof Error) // true
console.log(e.id) // "123"
console.log(e.name) // "MyError"
console.log(e.message) // "my message"
console.log(e.fileName) // "example.js"
console.log(e.lineNumber) // 20
console.log(e.stack) // "@Scratchpad/2:2:9\n"
}
(inner) xrequire(path, dirnullable, refnullable) → {any}
Extended require version, does not modify global require()
THIS METHOD ONLY WORK FOR COMMON.JS modules, and not for browser
- Does not throw when second argument
ref=ERR_NO_THROWprovided - ( Does not provide Intellisense unfortunately )
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
path |
string
|
require(>path<) |
|
dir |
string
|
<nullable> |
must provide |
ref |
string
|
<nullable> |
// ERR_NO_THROW and it wont throw an error |
Returns:
- Type:
-
any
module.require output or undefined
Example
xrequire('your_npm_package') // your npm package
xrequire('./path/to/module', __dirname) // your module script
xrequire('./blah/not/found', __dirname, 'ERR_NO_THROW') // returns undefined
xrequire('./blah/not/found', '', 'ERR_NO_THROW') // returns undefined
Type Definitions
callback()
- Source:
logType
- Source:
Type:
-
'log'|'warn'|'onerror'|'error'|'alert'|'attention'|'debug'|'stack'|'errorTrace'