index.js API documentation
Chainable
ChainedMapBase
DotProp
FactoryChain
MethodChain
Observe
ShorthandChain
Transform
Traverse
TraverseChain
add
addTypes
alias
anyKeyVal
argumentor
arithmeticTypeFactory
autoIncrement
builder
camelCase
clone
compose
concat
conditional
copy
debug
define
delete
dopemerge
entries
from
get
getMeta
if
includes
is
is.
is.arrayOf
is.exports
is.hasIn
is.isArray
is.isAsync
is.isAsyncish
is.isBoolean
is.isBooleanPrimitive
is.isDate
is.isDot
is.isEnumerable
is.isError
is.isFalse
is.isFunction
is.isIn
is.isIterator
is.isMap
is.isMapish
is.isMatcher
is.isNull
is.isNullOrUndefined
is.isNumber
is.isNumberPrimitive
is.isObj
is.isObjLoose
is.isObjNotNull
is.isObjPure
is.isObjWithKeys
is.isPromise
is.isPrototypeOf
is.isReal
is.isTrue
is.isUndefined
is.primitive$2
is.string
is.stringOrNumber
is.stringPrimitive
is.symbol
is.index$12
isNotRealOrIsEmpty
iteratable
keysObjOrArray
lengthFromZero
markForGarbageCollection
meta
method
methodEncasingFactory
noop
notNested
paths
pooler.// const pooler
reduce
regexp
schemaFactory
scopedEncase
set
set$$2
setChosen
simpleKindOf
test
this.extend
toArr
toTest
traverse
traversed
typedOnCall
types
util
validators
while
Chainable
Chainable.Chainable
Ⓢ Ⓣ
(Chainable): Trait class that can inherit any class passed into compose, extended by ChainedMap & ChainedSet
@see
@classProps
- {parent}
- {className}
Chainable.clear([clearPropertiesThatAreChainLike=true])
Ⓢ Ⓣ
(Function): clears the map, goes through this properties, calls .clear if they are instanceof Chainable or Map
@see
- https://github.com/fliphub/flipchain/issues/2
- ChainedSet
- ChainedMap
- map-clear
Arguments
[clearPropertiesThatAreChainLike=true]
(|boolean): checks properties on the object, if they arechain-like
, clears them as well
Returns
(Chainable): @chainable
Example
const chain = new Chain()
chain.set('eh', 1)
chain.entries()
//=> {eh: 1}
chain.clear()
chain.entries()
//=> {}
Chainable.delete(key=undefined)
Ⓢ Ⓣ
(Function): calls .delete on this.store.map
@see
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has
- ChainedSet
- ChainedMap
@Since
0.3.0
Arguments
key=undefined
(Primitive): on a Map: key referencing the value. on a Set: the index
Returns
(Chainable):
Example
const chain = new Chain()
chain.set('eh', 1)
chain.get('eh')
// => 1
chain.delete('eh', 1)
chain.get('eh')
// => undefined
Chainable.end()
Ⓢ Ⓣ
(Function): for ending nested chains
@see
@Since
0.4.0
Returns
(*):
Example
const parent = 'eh'
const child = newChain(parent)
child.end()
//=> 'eh'
Chainable.has(keyOrValue=undefined)
Ⓢ Ⓣ
(Function): checks whether the store has a value for a given key
@see
@Since
0.3.0
Arguments
keyOrValue=undefined
(any): key when Map, value when Set
Returns
(boolean):
Example
const chain = new Chain()
chain.set('eh', 1).has('eh')
//=> true
chain.has('canada')
//=> false
Chainable.length()
Ⓢ Ⓣ
Function
@see
@Since
0.5.0
Returns
(number):
Example
for (var i = 0; i < chain.length; i++)
Chainable.prototypeiterator
Ⓢ Ⓣ
(generator): Iterator for looping values in the store
@see
- https://github.com/sindresorhus/quick-lru/blob/master/index.js
- https://stackoverflow.com/questions/36976832/what-is-the-meaning-of-symbol-iterator-in-this-context
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator
- this.store
@notes
- assigned to a variable so buble ignores it
@Since
0.5.0
Returns
(Object): {value: undefined | any, done: true | false}
Example
const chain = new Chain().set('eh', 1)
for (var [key, val] of chain) console.log({ [key]: val })
//=> {eh: 1}
Example
*[Symbol.iterator](): void { for (const item of this.store) yield item }
Example
const { ChainedSet } = require('chain-able')
const set = new ChainedSet()
set.add('eh')
for (const arr of set) {
const [key, val] = arr
key
//=> 0
val
//=> 'eh'
arr.length
//=> 2
}
Chainable.prototypeprimitive
Ⓢ Ⓣ
(Function): symbol method for toString, toJSON, toNumber
@see
@Since
1.0.2
Arguments
hint=undefined
(string): enum[default, string, number]
Returns
(Primitive):
Example
const chain = new Chain()
chain.toNumber = () => 1 + chain
//=> 1
chain + 1
//=>
Example
const chain = new Chain()
chain.toString = () => 'eh'
chain + ''
//=> 'eh'
Chainable.values()
Ⓢ Ⓣ
(Function): spreads the entries from ChainedMap.store.values allocates a new array, adds the values from the iterator
@see
@notes
- look at Chainable.constructor to ensure not to use
new Array...
- moved from ChainedMap and ChainedSet to Chainable @2.0.2
- this was [...] & Array.from(this.store.values())
@Since
0.4.0
Returns
(*): toArr(this.store.values())
Example
const chain = new Chain()
chain.set('eh', 1)
chain.values()
//=> [1]
Chainable.when(condition=undefined, [trueBrancher=Function], [falseBrancher=Function])
Ⓢ Ⓣ
(Function): when the condition is true, trueBrancher is called, else, falseBrancher is called
Arguments
condition=undefined
(boolean|string): when string, checks this.get[trueBrancher=Function]
(Function): called when true[falseBrancher=Function]
(Function): called when false
Returns
(Chainable): @chainable
Example
const prod = process.env.NODE_ENV === 'production'
chains.when(prod, c => c.set('prod', true), c => c.set('prod', false))
ChainedMapBase
ChainedMapBase.ComposeChainedMap([SuperClass=ChainedMapBase])
Ⓢ Ⓣ
(Function): ChainedMap composer
@see
@extends
ChainedMapBase
@Since
0.0.1
Arguments
[SuperClass=ChainedMapBase]
(Class|Composable|Object): class to extend
Returns
(Class): ChainedMap
Example
const heh = class {}
const composed = ChainedMap.compose(heh)
const hehchain = new Composed()
hehchain instanceof heh
//=> true
ChainedMapBase.ComposeChainedMapBase
Ⓢ Ⓣ
(Chainable): this is to avoid circular requires because MergeChain & MethodChain extend this yet .method & .merge use those chains ...also, it serves as a non-references creator for extending new instances of Chainable, where it splits into (Map | Set) -> composed prototype decorators
@see
@classProps
- {meta} meta fn
- {store} main store
@extends
Chainable
@Since
4.0.0-alpha.1
ChainedMapBase.cmc([Target=Chainable])
Ⓢ Ⓣ
(Composer): ChainedMapBase composer
Arguments
[Target=Chainable]
(Class|Composable|Object): class to extend
Returns
(Class): ChainedMapBase
Example
const heh = class {}
const composed = ChainedMapBase.compose(heh)
const hehchain = new Composed()
hehchain instanceof heh
//=> true
ChainedMapBase.entries([chains=false])
Ⓢ Ⓣ
(Function): spreads the entries from ChainedMapBase.store (Map) return store.entries, plus all chain properties if they exist
@see
@Since
0.4.0
Arguments
[chains=false]
(boolean): if true, returns all properties that are chains
Returns
(Object): reduced object containing all properties from the store, and when chains
is true, all instance properties, and recursive chains
//
Example
map.set('a', 'alpha').set('b', 'beta').entries()
//=> {a: 'alpha', b: 'beta'}
ChainedMapBase.extend(methods=undefined)
Ⓢ Ⓣ
(Function): shorthand methods, from strings to functions that call .set
@Since
0.4.0
Arguments
methods=undefined
(string[]): decorates/extends an object with new shorthand functions to get/set
Returns
(ChainedMapBase): @chainable
Example
const chain1 = new Chain()
chain1.extend(['eh'])
const chain2 = new Chain()
chain2.eh = val => this.set('eh', val)
eq(chain2.eh, chain1.eh)
//=> true
ChainedMapBase.from(obj=undefined)
Ⓢ Ⓣ
(Function): checks each property of the object calls the chains accordingly
@todos
- [ ] could also add parsing stringified
@Since
0.5.0
Arguments
obj=undefined
(Object): object with functions to hydrate from
Returns
(Chainable): @chainable
Example
const from = new Chain().from({ eh: true })
const eh = new Chain().set('eh', true)
eq(from, eh)
// => true
ChainedMapBase.get(key=undefined)
Ⓢ Ⓣ
(Function): get value for key path in the Map store ❗ debug
is a special key and is not included into .store it goes onto .meta
@see
@Since
0.4.0
Arguments
key=undefined
(Primitive): Primitive data key used as map property to reference the value
Returns
(any): value in .store at key
Example
const chain = new Chain()
chain.set('eh', true)
chain.get('eh')
//=> true
chain.get('nope')
//=> undefined
ChainedMapBase.set(key=undefined, value=undefined)
Ⓢ Ⓣ
(Function): sets the value using the key on store adds or updates an element with a specified key and value
@see
@Since
0.4.0
Arguments
key=undefined
(Primitive): Primitive to reference the valuevalue=undefined
(any): any data to store
Returns
(ChainedMapBase): @chainable
Example
const chain = new Chain()
chain.set('eh', true)
chain.get('eh')
//=> true
ChainedMapBase.tap(name=undefined, fn=undefined)
Ⓢ Ⓣ
(Function): tap a value with a function
@see
@Since
4.0.0-alpha.1 <- moved from transform & shorthands
Arguments
name=undefined
(any|string): key to.get
fn=undefined
(Function): function to tap with
Returns
(Chain): @chainable
Example
chain
.set('moose', { eh: true })
.tap('moose', moose => {
moose.eh = false
return moose
})
.get('moose')
// => {eh: false}
Example
const entries = new Chain()
.set('str', 'emptyish')
.tap('str', str => str + '+')
.set('arr', [1])
.tap('arr', arr => arr.concat([2]))
.entries()
//=> {str: 'emptyish+', arr: [1, 2]}
ChainedSet
ChainedSet.ChainedSet
Ⓢ Ⓣ
Set
@see
- http://2ality.com/2015/09/well-known-symbols-es6.html
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/isConcatSpreadable
- Chainable
@notes
- had Symbol.isConcatSpreadable but it was not useful
@todos
- [ ] could add .first .last ?
@classProps
- {store}
@extends
Chainable
ChainedSet.add(value=undefined)
Ⓢ Ⓣ
(Function): appends a new element with a specified value to the end of the .store
@see
@Since
0.4.0
Arguments
value=undefined
(any): any value to add to **end** of the store
Returns
(ChainedSet): @chainable
Example
const people = new ChainedSet()
people.add('sam').add('sue')
for (let name of people) console.log(name)
//=> sam, sue
ChainedSet.merge(arr=undefined)
Ⓢ Ⓣ
(Function): merge any Array/Set/Iteratable/Concatables into the array, at the end
@Since
0.4.0
Arguments
arr=undefined
(Array|Concatable|Set): values to merge in and append
Returns
(ChainedSet): @chainable
Example
const people = new ChainedSet()
people.add('sam').add('sue').prepend('first').merge(['merged'])
for (let name of people) console.log(name)
//=> first, sam, sue, merged
ChainedSet.prepend(value=undefined)
Ⓢ Ⓣ
(Function): inserts the value at the beginning of the Set
@Since
0.4.0
Arguments
value=undefined
(any): any value to add to **beginning** the store
Returns
(ChainedSet): @chainable
Example
const people = new ChainedSet()
people.add('sue').prepend('first')
for (let name of people) console.log(name)
//=> first, sue
DotProp
DotProp.get(key=undefined, [fallback=undefined])
Ⓢ Ⓣ
(Function): dot-prop enabled get
@see
@todos
- [ ] dot-prop on non-store instance.property when using nested chains...
@Since
3.0.1
Arguments
key=undefined
(Primitive): dot prop key, or any primitive key[fallback=undefined]
(any): fallback value, if it cannot find value with key path
Returns
(any): value for path, or fallback value if provided
Example
chain.set('moose.simple', 1)
//=> Chain
chain.get('moose.simple')
//=>1
chain.get('moose')
//=> {simple: 1}
Example
//also works with an array (moose.simple)
chain.get(['moose', 'simple'])
//=> 1
FactoryChain
FactoryChain.chainUpDowns(methods=undefined)
Ⓢ Ⓣ
(Function): chain back up to parent for any of these
@todos
- [ ] should have a debug log for this
@Since
2.0.0
Arguments
methods=undefined
(string[]): methods to triggeronChainUpDown
on
Returns
(FactoryChain): @chainable
Example
const { Chain, FactoryChain, ChainedSet } = require('chain-able')
class Things extends Chain {
constructor(parent) {
super(parent)
this.people = new ChainedSet(this)
}
person() {
const person = new FactoryChain(this)
person
.props(['name', 'age', 'email'])
.onChainUpDown(this.person)
.chainUpDowns(['person'])
.onDone(personChain => {
this.people.add(personChain)
return this
})
return person
}
}
const things = new Things()
const returned = things
.person()
.name('sue')
.person()
.age(100)
.name('john')
.email('@')
FactoryChain.factory([obj={}])
Ⓢ Ⓣ
(Function): creates/add the .end
method, which checks how many methods have been called, and decides whether to return parent or not
@Since
2.0.0
Arguments
[obj={}]
(Object): optional object to use for creating .end
Returns
(FactoryChain): @chainable
FactoryChain.getData([prop=undefined])
Ⓢ Ⓣ
(Function): access data being built when stepping through a factory
@Since
2.0.0
Arguments
[prop=undefined]
(Primitive): key of the data, or returns all data
Returns
(any): this.data
Example
.data['prop'] = 'eh'
.getData('prop')
//=> 'eh'
.getData()
//=> {prop: 'eh'}
Example
const person = new FactoryChain(this)
const age = person.props(['name', 'age']).age(10).getData('age')
expect(age).toBe(10)
FactoryChain.prop(name=undefined, [onCall=undefined])
Ⓢ Ⓣ
(Function): add property that are counted towards the call count for easy auto-ending chaining
@Since
2.0.0
Arguments
name=undefined
(Primitive): property name[onCall=undefined]
(||Function): callback for the property
Returns
(FactoryChain): @chainable
Example
person
//.prop also accepts an optional callback,
//for nestable nestable chains
.prop('name')
.prop('age')
.prop('email')
FactoryChain.props(names=undefined)
Ⓢ Ⓣ
(Function): adds an array of properties, using FactoryChain.prop
@see
@Since
2.0.0
Arguments
names=undefined
(string[]): property names
Returns
(FactoryChain): @chainable
Example
person.props(['name', 'age', 'email'])
typeof person.name
//=> 'function'
person.name().age()
//=> FactoryChain
person.name().age().email()
//=> ParentChain
// person.name().age().person()
//=> FactoryChain
//^ because .person is `chainUpDowns`
//^ so it finishes the old chain, and begins a new one
MergeChain
MergeChain.MergeChain
Ⓢ Ⓣ
Map
@see
@todos
- [ ] consider just making this a function,
because 80/20 onValue merger & onExisting are rarely used & are easily overridable with .merge
@extends
ChainedMapBase
@Since
1.0.0
MergeChain.init(opts=undefined)
Ⓢ Ⓣ
(Function): options for merging with dopemerge
@see
@Since
1.0.2
Arguments
opts=undefined
(Function|Object): when object: options for the merger. when function: is the merger
Returns
(MergeChain): @chainable
Example
{
stringToArray: true,
boolToArray: false,
boolAsRight: true,
ignoreTypes: ['null', 'undefined', 'NaN'],
debug: false,
}
Example
.merger(require('lodash.mergewith')())
MethodChain
MethodChain.MethodChain
Ⓢ Ⓣ
(Map): ❗ using +
will call .build()
in a shorthand fashion
@todos
- [ ] maybe abstract the most re-usable core as a protected class
so the shorthands could be used, and more functionality made external
- [ ] need to separate schema from here as external functionality & add .add
- [ ] .prop - for things on the instance, not in the store?
!!! .sponge - absorn properties into the store
@extends
ChainedMap
@Since
4.0.0
MethodChain._build(name=undefined, parent=undefined)
Ⓢ Ⓣ
Function
@notes
- scoping here adding default functions have to rescope arguments
@todos
- [ ] allow config of method var in plugins since it is scoped...
- [ ] add to .meta(shorthands)
- [ ] reduce complexity if perf allows
@Since
4.0.0-alpha.1
Arguments
name=undefined
(Primitive):parent=undefined
(Object):
Returns
(void):
MethodChain._defaults(name=undefined, parent=undefined, built=undefined)
Ⓢ Ⓣ
Function
@todos
- [ ] optimize the size of this
with some bitwise operators hashing the things that have been defaulted also could be plugin
@Since
4.0.0
Arguments
name=undefined
(Primitive): method nameparent=undefined
(Object): being decoratedbuilt=undefined
(Object): method being built
Returns
(void):
Example
._defaults('', {}, {})
Example
let methodFactories
### `onSet`
> defaults to `this.set(key, value)`
```ts
public onSet(fn: Fn): MethodChain
onCall
defaults to .onSet ^
public onCall(fn: Fn): MethodChain
onGet
defaults to
this.get(key)
public onGet(fn: Fn): MethodChain
---
<!-- /div -->
<!-- div -->
<h3 id="MethodChain-prototype-autoGetSet" data-member="MethodChain" data-category="Methods" data-name="autoGetSet"><code>MethodChain.autoGetSet(name=undefined, parent=undefined)</code></h3>
<br>
<br>
[Ⓢ](https://github.com/fluents/chain-able/blob/master/dists/dev/index.js#L7039 "View in source") [Ⓣ][1]
Function
#### @see
* <a href="https://github.com/fluents/chain-able/blob/master/src/MethodChain.js" >MethodChain</a>
#### Arguments
1. `name=undefined` *(Primitive)*: method name being built
2. `parent=undefined` *(Object)*: parent containing the method
#### Returns
*(MethodChain)*: @chainable
#### Example
```js
const chain = new Chain()
chain.methods('eh').plugin(autoGetSet).build()
chain.eh(1)
//=> Chain
chain.eh()
//=> 1
MethodChain.autoIncrement()
Ⓢ Ⓣ
(Function): adds a plugin to increment the value on every call
@see
@Since
0.4.0
Returns
(MethodChain): @chainable
Example
chain.methods(['index']).autoIncrement().build().index().index(+1).index()
chain.get('index')
//=> 3
MethodChain.build([returnValue=undefined])
Ⓢ Ⓣ
(Function): set the actual method, also need .context - use .parent
@see
@todos
- [ ] if passing in a name that already exists, operations are decorations... (partially done)
@Since
4.0.0
Arguments
[returnValue=undefined]
(any): returned at the end of the function for ease of use
Returns
(MethodChain): @chainable
Example
var obj = {}
const one = new MethodChain(obj).methods('eh').getSet().build(1)
//=> 1
typeof obj.getEh
//=> 'function'
MethodChain.decorate(parentToDecorate=undefined)
Ⓢ Ⓣ
(Function): decorates a parent when the argument is provided BUT THE FUNCTIONS WILL STILL BE SCOPED TO CURRENT PARENT for easy factory chaining
@see
@todos
- [ ] this is more like a preset since it adds plugins?
more of methodFactory now
@Since
4.0.0-alpha.1
Arguments
parentToDecorate=undefined
(Object): object to put the method on instead
Returns
(MethodChain): @chainable
Example
const chain = new Chain()
const obj = {}
chain.method('ehOh').decorate(obj).build()
typeof obj.ehOh
//=> 'function'
MethodChain.decorate([parentToDecorate=undefined])
Ⓢ Ⓣ
(Function): add methods to the parent for easier chaining
@see
- plugins/decorate
- ChainedMap.parent
Arguments
[parentToDecorate=undefined]
(Object): decorate a specific parent shorthand
Returns
(ChainedMap): @chainable
Example
var obj = {}
new MethodChain({}).name('eh').decorate(obj).build()
typeof obj.eh
//=> 'function'
Example
class Decorator extends Chain {
constructor(parent) {
super(parent)
this.methods(['easy']).decorate(parent).build()
this.methods('advanced')
.onCall(this.advanced.bind(this))
.decorate(parent)
.build()
}
advanced(arg) {
this.set('advanced', arg)
return this.parent
}
easy(arg) {
this.parent.set('easy-peasy', arg)
}
}
class Master extends Chain {
constructor(parent) {
super(parent)
this.eh = new Decorator(this)
}
}
const master = new Master()
master.get('easy-peasy')
//=> true
master.eh.get('advanced')
//=> 'a+'
Example
;+chain.method('ehOh').decorate(null)
//=> @throws Error('must provide parent argument')
MethodChain.name(methods=undefined)
Ⓢ Ⓣ
(Function): setup methods to build
Arguments
methods=undefined
(Object|string|string[]): method names to build
Returns
(MethodChain): @chainable
Example
var obj = {}
new MethodChain(obj).name('eh').build()
typeof obj.eh
//=> 'function'
MethodChain.schema(obj=undefined)
Ⓢ Ⓣ
(Function): an object that contains nestable .type
s they are recursively (using an optimized traversal cache) mapped to validators ❗ this method auto-calls .build, all other method config calls should be done before it
@todos
- [ ] link to
deps/is
docs - [ ] move out into a plugin to show how easy it is to use a plugin
and make it able to be split out for size when needed
- [ ] inherit properties (in plugin, for each key)
from this for say, dotProp, getSet
- [ ] very @important
that we setup schema validation at the highest root for validation and then have some demo for how to validate on set using say mobx observables for all the way down...
@Since
4.0.0
Arguments
obj=undefined
(Object): schema
Returns
(MethodChain): @chainable
Example
chain
.methods()
.define()
.getSet()
.onInvalid((error, arg, instance) => console.log(error))
.schema({
id: '?number',
users: '?object|array',
topic: '?string[]',
roles: '?array',
creator: {
name: 'string',
email: 'email',
id: 'uuid',
},
created_at: 'date',
updated_at: 'date|date[]',
summary: 'string',
})
//--- valid
chain.created_at = new Date()
chain.setCreatedAt(new Date())
isDate(chain.created_at) === true
//--- nestable validation 👍
chain.merge({ creator: { name: 'string' } })
//--- invalid
chain.updated_at = false
Observe
Observe.observe(properties=undefined, fn=undefined)
Ⓢ Ⓣ
(Function): observe properties when they change
@see
@todos
- [ ] gotta update
data
ifdeleting
too... - [ ] un-observe
- [ ] should hash these callback properties
- [ ] just throttle the
.set
to allow easier version of .commit
Arguments
properties=undefined
(Matchable): Matchable properties to observefn=undefined
(Function): onChanged
Returns
(Target): @chainable
Example
const Target = require('chain-able')
const chain = new Target()
const log = arg => console.log(arg)
chain.extend(['eh']).observe('eh', data => log(data)).eh(true)
//=> {eh: true}
Example
chain
.extend(['canada', 'timbuck'])
.observe(['canad*'], data => console.log(data.canada))
.canada(true)
.canada(true)
.timbuck(false)
//=> true
//=> false
// only called when changed,
// otherwise it would be 2 `true` & 1 `false`
Observe.DotProp(Target=undefined)
Ⓢ Ⓣ
Function
@see
@extends
ChainedMap
Arguments
Target=undefined
(Class|Composable): composable class
Returns
(DotProp): class
Example
const { compose } = require('chain-able')
const { DotProp } = compose
new DotProp()
//=> DotProp
Example
const chain = new Chain()
chain.set('moose.simple', 1)
//=> Chain
chain.get('moose.simple')
//=>1
chain.get('moose')
//=> {simple: 1}
chain.set('moose.canada.eh', true).set('moose.canada.igloo', true)
//=> Chain
//set, has, get, delete :-)
chain.delete('moose.canada.eh')
//=> Chain
//also works with an array (moose.canada.igloo)
chain.get(['moose', 'canada', 'igloo'])
//=> true
Observe.Observe(Target=undefined)
Ⓢ Ⓣ
(Function): > subscribe to changes ❗ called only on change observers are only called when data they subscribe to changes
@see
- ChainedMap
- DotProp
- deps/matcher
- deps/traversers/eq
- deps/traverse
- DotProp
- reactivex
- awesome-observables
- building-observables
- observer-pattern
- observable-air
@extends
- ChainedMap
- DotProp
@Since
3.0.1
Arguments
Target=undefined
(Class|Composable): composable class
Returns
(Observe): class
Example
const { compose } = require('chain-able')
const { DotProp } = compose
new DotProp()
//=> DotProp
ShorthandChain
ShorthandChain.return(value=undefined)
Ⓢ Ⓣ
(Function): returns any value passed in return a value at the end of a chain regardless
@Since
3.0.0
Arguments
value=undefined
(any): value to return at the end of a chain
Returns
(any): value
Example
const chain = new Chain()
const saveAndDebug = env =>
chain.from({ env: env.NODE_ENV }).return(JSON.stringify(env))
console.log(saveAndDebug(process.env))
//=> value of process.env
ShorthandChain.setIfEmpty(name=undefined, value=undefined)
Ⓢ Ⓣ
(Function): sets a value only when .has is false aka set if the value has not been set
@see
@Since
1.0.2
Arguments
name=undefined
(Primitive): key to set if it has not been done so alreadyvalue=undefined
(any): value to set when key has not been already set
Returns
(ShorthandChain): @chainable
Example
const chain = new Chain()
chain.set('eh', true)
// eh is already set ^, ignored
chain.setIfEmpty('eh', false)
chain.get('eh')
//=> true
Example
new Chain().setIfEmpty('canada', true).entries()
//=> {canada: true}
Example
// longhand way to do the same thing
if (chain.has('eh') === false) {
chain.set('eh', false)
}
// or using .when
chain.when(!chain.has('eh'), instance => instance.set('eh', false))
ShorthandChain.wrap(fn=undefined)
Ⓢ Ⓣ
(Function): wrap a value, if it's a Function call it, return this aka execute something and return this
@Since
2.0.0
Arguments
fn=undefined
(Function|any): function to call, or just any value
Returns
(ShorthandChain): @chainable
Example
const { eh } = chain.wrap(chain => (chain.eh = true))
//=> true
Example
new Chain()
.wrap(
encased =>
(encased.fn = arg => {
throw new Error('encased yo')
})
)
.method('fn')
.encase()
.catch(error => {
//=> Error('encasedYo')
})
.build()
.fn(true)
Transform
TransformChain
TransformChain.remap(from=undefined, [to=undefined])
Ⓢ Ⓣ
(Function): remap properties from 1
to another, for example, apis with inconsistent naming
@see
@symb
🗺
@Since
1.0.0
Arguments
from=undefined
(Object|string): property name string, or {[from]: to}[to=undefined]
(string): property name to change key to
Returns
(Chain): @chainable
Example
chain.remap('dis', 'dat').from({ dis: true })
chain.entries()
//=> {dat: true}
Example
chain
.remap({dis: 'dat'})
.from({dis: 1, other: true}}
chain.entries()
//=> {dist: 1, other: true}
TransformChain.set(key=undefined, val=undefined, dotPropKey=undefined)
Ⓢ Ⓣ
Function
@see
@Since
1.0.0
Arguments
key=undefined
(Primitive): key to set withval=undefined
(any): value to set for keydotPropKey=undefined
(|string|string[]): special key used for initializing dot prop values in an optimized way to keep reference
Returns
(Chainable): @chainable
TransformChain.transform(key=undefined, value=undefined)
Ⓢ Ⓣ
Function
@todos
- [ ] dot-prop here
@Since
1.0.2
Arguments
key=undefined
(Function|string): currently just stringvalue=undefined
(Function): callback accepting the value as only arg to transform with
Returns
(TransformChain): @chainable
Example
// coerce values with .id into the value they hold
chain.transform('dis', val => (typeof val === 'string' ? val : val.id))
chain.set('dis', 'eh')
chain.get('dis')
//=> 'eh'
chain.set('dis', { id: 'eh' })
chain.get('dis')
//=> 'eh'
Example
import { format } from 'date-fns/esm'
import { Chain } from 'chain-able'
const chain = new Chain()
chain.transform('created_at', date => format(date, 'MM/DD/YYYY'))
chain.set('created_at', new Date())
// is formatted human-readable pretty!
const { created_at } = chain.entries()
//=> '02/11/2014'
Traverse
Traverse.TraverseChain
Ⓢ Ⓣ
Map
@see
@symb
👣
@classProps
- {obj}
- {keys}
- {vals}
- {onMatch}
- {onNonMatch}
- {clone}
@extends
ChainedMapBase
@Since
1.0.0
Traverse.checkIteratable(node=undefined)
Ⓢ Ⓣ
(Function): checks whether a node is iteratable
@todos
- [ ] move into the wrapper? if perf allows?
Arguments
node=undefined
(*): value to check
Returns
(void):
Example
.checkIteratable({eh: true})
//=> this.isLeaf = false
//=> this.isCircular = false
//=> this.isIteratable = true
.checkIteratable({} || [])
//=> this.isLeaf = true
//=> this.isCircular = false
//=> this.isIteratable = false
var circular = {}
circular.circular = circular
.checkIteratable(circular)
//=> this.isLeaf = false
//=> this.isCircular = true
//=> this.isIteratable = true
Traverse.clone(arg=undefined)
Ⓢ Ⓣ
(Function): clone any value
@see
@extends
- undefined
- undefined
@Since
4.0.0
Arguments
arg=undefined
(*): argument to clone
Returns
(*): cloned value
Example
var obj = { eh: true }
clone(obj) === obj //=> false
var obj = { eh: true }
var obj2 = clone(obj)
obj.eh = false
console.log(obj2.eh) //=> true
Traverse.copy(src=undefined)
Ⓢ Ⓣ
(Function): copy any primitive value, part of clone
@see
@Since
3.0.0
Arguments
src=undefined
(*): value to copy
Returns
(*): copied
Example
copy(/eh/gim) //=> new RegExp('eh', 'gmi')
copy(new Error('eh')) // => new Error with copied stack + msg
copy([1]) // => [1]
copy({}) // => {}
Traverse.eq(traverse=undefined, a=undefined, b=undefined, [loose=undefined])
Ⓢ Ⓣ
Function
@see
- immutable-js-deep-equal
- node-deep-equal
- ramda-equals
- lodash-is-equal
- angular-is-equal
- underscore-equal
- traverse-deep-equal
- react-deep-differ
@extends
@Since
3.0.0
Arguments
traverse=undefined
(Traverse): traversejs *(scoped, @FIXME @HACK)*a=undefined
(*): compare to bb=undefined
(*): compare to a[loose=undefined]
(boolean): compare loosely
Returns
(boolean): isEqual: a === b
Example
eq(1, 1) //=> true
eq(1, '1') //=> false
eq(1, '1', true) //=> true
eq([1], [1]) //=> true
Traverse.eqValue(x=undefined, y=undefined, [loose=false])
Ⓢ Ⓣ
(Function): checks value equality, used by eq which compares all types
@todos
- [ ] !!!!!! USE ENUM FLAGS ON LOOSE TO ALLOW MORE CONFIG FOR ==, COMPARATOR, VALUEOF, walk proto (check ownProps...)...
@Since
4.1.0
Arguments
x=undefined
(*): compare to yy=undefined
(*): compare to x[loose=false]
(boolean|number): use == checks when typof !=
Returns
(boolean):
Example
eqValue(1, 1) //=> true
eqValue('1', 1) //=> false
eqValue('1', 1, true) //=> true
eqValue({}, {}) //=> true
Traverse.forEach(cb=undefined)
Ⓢ Ⓣ
(Function): this is the main usage of Traverse
@Since
3.0.0
Arguments
cb=undefined
(Function): callback for each iteration
Returns
(*): mapped result or original value, depends how it is used
Example
traverse([1, 2, 3]).forEach((key, value) => console.log({ [key]: value }))
//=> {'0': 1}
//=> {'1': 2}
//=> {'2': 3}
Traverse.iterate(on=undefined)
Ⓢ Ⓣ
Function
@todos
- [ ] handler for Set & Map so they can be skipped or traversed, for example when cloning...
- [ ] add hook to add custom checking if isIteratable
- [ ] deal with .isRoot if needed
- [ ] examples with clone and stop
@sig
on(key: null | Primitive, val: any, instance: Traverse): any
Arguments
on=undefined
(Function): callback fn for each iteration
Returns
(*): this.node
Example
iterate([])
//=> []
//=> on(null, [])
Example
iterate([1])
//=> [1]
//=> on(null, [1])
//=> on('1', 1)
Example
//primitive - same for any number, string, symbol, null, undefined
iterate(Symbol('eh'))
//=> Symbol('eh')
//=> on(Symbol('eh'))
Example
var deeper = { eh: 'canada', arr: [{ moose: true }, 0] }
iterate(deeper)
//=> deeper // returns
//=> on(null, deeper, this) // root
//=> on('eh', 'canada', this) // 1st branch
//=> on('arr', [{moose: true}, 0], this)
//=> on('arr.0', [{moose: true}], this)
//=> on('arr.0.moose', true, this)
//=> on('arr.1', [0], this)
Traverse.remove([arg=undefined])
Ⓢ Ⓣ
(Function): Remove the current element from the output. If the node is in an Array it will be spliced off. Otherwise it will be deleted from its parent.
@Since
2.0.0
Arguments
[arg=undefined]
(|Object): optional obj to use, defaults to this.node
Returns
(void):
Example
traverse([0]).forEach((key, val, it) => it.remove())
//=> []
traverse({ eh: true }).forEach((key, val, it) => it.remove())
//=> {}
traverse({ eh: true, str: 'stringy' }).forEach((key, val, it) => {
if (!isString(val)) it.remove()
})
//=> {str: 'stringy'}
Traverse.skip()
Ⓢ Ⓣ
Function
@todos
- [ ] skip 1 branch
@Since
3.0.0
Returns
(void):
Example
traverse([1, 2, 3, [4]]).forEach((key, val, t) => {
if (isArray(val)) t.skip()
})
Traverse.stop()
Ⓢ Ⓣ
(Function): stop the iteration
Returns
(void):
Example
traverse({ eh: true, arr: [] }).forEach((key, val, t) => {
if (isArray(val)) this.stop()
})
Traverse.update(value=undefined)
Ⓢ Ⓣ
(Function): update the value for the current key
@Since
2.0.0
Arguments
value=undefined
(*): this.node[this.key] = value
Returns
(void):
Example
traverse({ eh: true }).forEach((key, val, traverser) => {
if (this.isRoot) return
traverser.update(false)
})
//=> {eh: false}
TraverseChain
TraverseChain.traverse([shouldReturn=false])
Ⓢ Ⓣ
(Function): runs traverser, checks the tests, calls the onMatch
@Since
1.0.0
Arguments
[shouldReturn=false]
(boolean): returns traversed object
Returns
(any): this.obj/data cleaned
Example
const traversed = new Chain()
.merge({ flat: 0, one: { two: true } })
.traverse(false)
.vals([/true/])
.onMatch((current, traverser) => {
traverser.path.join('.')
//=> 'one.two'
current
//=> true
typeof traverser.update === typeof traverser.remove
typeof traverser.update === 'function'
//=> true
traverser.remove()
//=> void
})
.onNonMatch(val => {
// ignore
})
.call(true)
traversed
//=> {flat: 0}
add
add(methodFactory=undefined)
Ⓢ Ⓣ
(Function): add methodFactories easily
@Since
4.0.0-beta.2
Arguments
methodFactory=undefined
(Object): factories to add
Returns
(void):
Example
function autoGetSet(name, parent) {
const auto = arg =>
isUndefined(arg) ? parent.get(name) : parent.set(name, arg)
//so we know if we defaulted them
auto.autoGetSet = true
return this.onSet(auto).onGet(auto).onCall(auto)
}
MethodChain.addPlugin({ autoGetSet })
const chain = new Chain()
chain.methods('eh').autoGetSet().build()
chain.eh(1)
//=> chain
chain.eh()
//=> 1 *
addTypes
addTypes(types=undefined)
Ⓢ Ⓣ
(Function): add custom types for validation
@see
- deps/validators/validatorFactory
Arguments
types=undefined
(Object): custom Types
Example
addTypes({ yaya: x => typeof x === 'string' })
const chain = new Chain().methods('eh').type('yaya').build()
chain.eh('good')
//=> chain
chain.eh(!!'throws')
//=> TypeError(false != {yaya: x => typeof x === 'string'})
Example
const custom = {}
custom.enums = enums => x => enums.includes(x)
custom['*'] = x => true
addTypes(custom)
//-> void
new Chain().methods('eh').type('*').build().eh
//=> validateType(custom['*'])
alias
alias(aliases=undefined)
Ⓢ Ⓣ
(Function): alias methods
@notes
- these would be .transform
@Since
2.0.0
Arguments
aliases=undefined
(string|string[]): aliases to remap to the current method being built
Returns
(MethodChain): @chainable
Example
const chain = new Chain()
chain.methods(['canada']).alias(['eh']).build()
chain.eh('actually...canada o.o')
chain.get('canada')
//=> 'actually...canada o.o')
anyKeyVal
anyKeyVal(keys=undefined, vals=undefined)
Ⓢ Ⓣ
(Function): the original simple to-test matcher for traversable, will be merged into, or simplified as simplified into matcher
@todos
- [ ] should use matcher,
- [ ] should inprove the callback data...
@Since
2.0.0
Arguments
keys=undefined
(Matchable[]): matchable keysvals=undefined
(Matchable[]): matchable values
Returns
(boolean): matched or not
Example
anyKeyVal([], [])(0, 0)
//=> false
anyKeyVal([() => true], [])(0, 0)
//=> true
argumentor
argumentor()
Ⓢ Ⓣ
(Function): turns arguments into an array, used as a util, for opt
@see
- https://github.com/aretecode/awesome-deopt
- https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
- deps/util/lengthFromZero
@Since
3.0.0
Returns
(*):
Example
function eh() {
const args = argumentor.apply(null, arguments).slice(1)
console.log(args)
//=> [1, 10, 100]
}
eh(0, 1, 10, 100)
arithmeticTypeFactory
arithmeticTypeFactory(fullKey=undefined)
Ⓢ Ⓣ
(Function): transform arithmetic strings into types
@see
@todos
- [ ] coercing values to certain types: arithmeticTypeFactory('
')
@Since
4.0.0-alpha.1
Arguments
fullKey=undefined
(Matchable): arithmetic type key
Returns
(Matchable): function to match with, with .inspect for easy debugging
Example
arithmeticTypeFactory('?string')
//=> x => !isReal(x) || isString(x)
Example
arithmeticTypeFactory('?string|string[]')
//=> x => isString(x) || isArrayOf(isString)(x)
Example
arithmeticTypeFactory('!string')
//=> x => not(isString)(x)
Example
types.addTypes({ star: x => true })
arithmeticTypeFactory('object|function|star')
//=> x => isObj(x) || isFunction(x) || isStar(x)
Example
arithmeticTypeFactory('===')
//=> x => (['===']).includes(x)
autoIncrement
builder
builder(fullKey=undefined)
Ⓢ Ⓣ
(Function): @pattern @builder -> builds using multiple factories depending on conditons or abstractFactory whatever opinionated: if it's a function, it's a validator...
@see
@notes
- if/else is for uglifying ternaries, even though else if is not needed
- if key is number, iterating the array
@Since
4.0.0
Arguments
fullKey=undefined
(Function|Primitive|string): arithmetic key to the validator
Returns
(Function): validator
Example
// functionType
const isString = x => typeof x === 'string'
builder(isString)
// => isString
Example
// stringType (built in, or custom-keyed validator, or eqeqeq)
builder('string')
// => isString
const enummy = builder('enum')
// => x => ['enum'].includes(x)
Example
// arithmeticType
builder('string|string[]')
// => isString || isArrayOf(isString)
camelCase
clone
clone(arg=undefined)
Ⓢ Ⓣ
Function
@todos
- [ ] merge with dopemerge?
- [ ] needs tests converted back for this (observe tests do cover somewhat)
Arguments
arg=undefined
(*): defaults to this.node
Returns
(*): cloned
Example
var obj = {}
var cloned = traverse().clone(obj)
obj.eh = true
eq(obj, cloned)
//=> false
compose
compose.compose([target=ChainedMap], [extensions=[Observe,Shorthands,Transform,DotProp]])
Ⓢ Ⓣ
(Function): compose chains all the way up from Chainable
@see
- https://formidable.com/blog/2017/infinite-state-composition-with-freactal/
- https://blog.javascripting.com/2016/02/02/encapsulation-in-redux/
- https://www.barbarianmeetscoding.com/blog/2016/01/04/safer-javascript-object-composition-with-traits-and-traits-dot-js/
- https://medium.com/javascript-scene/why-learn-functional-programming-in-javascript-composing-software-ea13afc7a257
- https://hackernoon.com/javascript-functional-composition-for-every-day-use-22421ef65a10
- https://github.com/stoeffel/awesome-fp-js
@symb
🎼
@Since
3.0.0
Arguments
[target=ChainedMap]
(|Class|Function): class or function to extend[extensions=[Observe,Shorthands,Transform,DotProp]]
(|Array): Array of extensions to compose together left to right
Returns
(*): composed
Example
class Eh extends compose() {}
new Eh() instanceof Chainable
//=> true
Example
class Target {}
class Eh extends compose(Target) {}
new Eh() instanceof Target
//=> true
Example
class Target {}
const mixin = SuperClass => class extends SuperClass {}
class Eh extends compose(Target) {}
new Eh() instanceof Chainable
//=> true
Example
class Winning {}
class Yes extends compose(Winning) {
get winning() {
return true
}
}
const yes = new Yes()
yes instanceof Winning && yes.winning
//=> true
concat
concat(one=undefined, two=undefined)
Ⓢ Ⓣ
(Function): concat two values, coerce to arrays
@Since
4.0.0
Arguments
one=undefined
(*|Array): toArr1two=undefined
(*|Array): toArr2
Returns
(Array): [one, two]
Example
concat([1], [2]) //=> [1, 2]
concat([1], 2) //=> [1, 2]
concat(1, 2) //=> [1, 2]
concat(new Set([1]), 2) //=> [1, 2]
// kind of weird...
concat(null, 2) //=> [2]
concat(undefined, 2) //=> [2]
concat(1, null) //=> [1, null]
conditional
conditional.all(predicate=undefined, array=undefined)
Ⓢ Ⓣ
(Function): map all values in an array to see if all match Returns true
if all elements of the list match the predicate, false
if there are any that don't.
@see
@todos
- [ ]
not(some)
?
@sig
(a -> Boolean) -> [a] -> Boolean
@Since
4.0.1
Arguments
predicate=undefined
(Function): match the valuearray=undefined
(Array): to match against predicate
Returns
(boolean): all match predicate
Example
const allBoolean = all(x => typeof x === 'boolean'q)
allBoolean([true])
//=> true
allBoolean([1])
//=> false
conditional.and(left=undefined, right=undefined)
Ⓢ Ⓣ
(Function): first fn & second fn
@Since
4.0.1
Arguments
left=undefined
(Function): first fnright=undefined
(Function): second fn
Returns
(boolean): both functions return truthy
Example
const both = and(x => typeof x === 'boolean', x => x === true)
both([true])
//=> true
both([false])
//=> false
both([1])
//=> false
conditional.not(fn=undefined, x=undefined)
Ⓢ Ⓣ
(Function): return a negated function A function wrapping a call to the given function in a !
operation. It will:
- return
true
when the underlying function would return a false-y value, - and
false
when it would return a truth-y one.
@Since
4.0.1
Arguments
fn=undefined
(Function): any functionx=undefined
(*): value to pass to function
Returns
(Function): !Function(x)
Example
const falsed = not(x => true)
const trued = not(x => false)
trued()
//=> true
falsed()
//=> false
conditional.or(left=undefined, right=undefined, x=undefined)
Ⓢ Ⓣ
(Function): first fn || second fn, curried
@Since
4.0.1
Arguments
left=undefined
(Function): first fnright=undefined
(Function): second fnx=undefined
(*): value to pass into left & right, curried
Returns
(boolean): one of the functions return truthy
Example
const { isTrue, isFalse } = require('chain-able')
const either = or(isFalse, isTrue)
either([true])
//=> true
either([new Boolean(true)])
//=> false
either([1])
//=> false
// because curried
or(isTrue, isFalse, true) //=> true
copy
debug
debug([should=true])
Ⓢ Ⓣ
(Function): sets on store not this.set for easier extension
@notes
- is inherited by any chain with a parent with .meta.debug
Arguments
[should=true]
(boolean): shouldDebug
Returns
(Chainable): @chainable
Example
const Chain = require('chain-able')
const chain = new Chain()
chain.debug()
chain.get('debug')
//=> true
// not in entries
chain.entries()
//=> {}
define
define(obj=undefined, name=undefined, descriptor=undefined)
Ⓢ Ⓣ
(Function): default to configurable and enumerable, unless configured otherwise
@Since
4.0.0
Arguments
obj=undefined
(Object): object to define onname=undefined
(Primitive): property name to definedescriptor=undefined
(Object): object descriptor
Returns
(void):
Example
var desc = Object.getOwnPropertyDescriptor(obj, 'eh', {
get: () => console.log('eh'),
})
delete
dopemerge
dopemerge.cloneIfNeeded(value=undefined, optsArg=undefined)
Ⓢ Ⓣ
(Function): Defaults to false
. If clone
is true
then both x
and y
are recursively cloned as part of the merge.
@see
@Since
2.0.0
Arguments
value=undefined
(*): value to clone if neededoptsArg=undefined
(DopeMergeOptions): dopemerge options, could contain .clone
Returns
(*): cloned or original value
Example
var obj = { eh: true }
cloneIfNeeded(obj, { clone: true }) === obj
//=> false
cloneIfNeeded(obj, { clone: false }) === obj
//=> true
dopemerge.defaultArrayMerge(target=undefined, source=undefined, optsArg=undefined)
Ⓢ Ⓣ
(Function): The merge will also merge arrays and array values by default. However, there are nigh-infinite valid ways to merge arrays, and you may want to supply your own. You can do this by passing an arrayMerge
function as an
option.
@Since
2.0.0
Arguments
target=undefined
(*): array merged onto, could be emptyTarget if cloningsource=undefined
(*): original source arrayoptsArg=undefined
(*): dopemerge options
Returns
(*): merged array
Example
function concatMerge(destinationArray, sourceArray, options) {
destinationArray
//=> [1, 2, 3]
sourceArray
//=> [3, 2, 1]
options
//=> { arrayMerge: concatMerge }
return destinationArray.concat(sourceArray)
}
merge([1, 2, 3], [3, 2, 1], { arrayMerge: concatMerge })
//=> [1, 2, 3, 3, 2, 1]
dopemerge.dopemerge(obj1=undefined, obj2=undefined, opts=undefined)
Ⓢ Ⓣ
(Function): Merge the enumerable attributes of two objects deeply. Merge two objects x
and y
deeply, returning a new merged object with the elements from both x
and y
. If an element at the
same key is present for both x
and y
, the value from
y
will appear in the result. Merging creates a new object, so that neither x
or y
are be modified. However, child objects on x
or y
are copied over - if you want to copy all
values, you must pass true
to the clone option.
@see
- deepmerge
Arguments
obj1=undefined
(*): leftobj2=undefined
(*): rightopts=undefined
(*): dopemerge options
Returns
(*): merged
Example
var x = {
foo: { bar: 3 },
array: [
{
does: 'work',
too: [1, 2, 3],
},
],
}
var y = {
foo: { baz: 4 },
quux: 5,
array: [
{
does: 'work',
too: [4, 5, 6],
},
{
really: 'yes',
},
],
}
var expected = {
foo: {
bar: 3,
baz: 4,
},
array: [
{
does: 'work',
too: [1, 2, 3, 4, 5, 6],
},
{
really: 'yes',
},
],
quux: 5,
}
merge(x, y)
//=> expected
dopemerge.emptyTarget(val=undefined)
Ⓢ Ⓣ
(Function): make a new empty Array or Object for cloning
@Since
2.0.0
Arguments
val=undefined
(*): array or object to return an empty one of
Returns
(*): depending on the data type of val
Example
emptyTarget({ eh: true })
//=> {}
emptyTarget([1])
//=> []
dopemerge.isMergeableObj(x=undefined)
Ⓢ Ⓣ
(Function): 1: not null object 2
: object toString is not a date or regex
@Since
2.0.0
Arguments
x=undefined
(*): value to check
Returns
(boolean):
Example
isMergeableObj({})
//=> true
isMergeableObj(Object.create(null))
// => true
isMergeableObj(new Date())
//=> false
isMergeableObj(/eh/)
//=> false
dot
dot([useDot=undefined])
Ⓢ Ⓣ
Function
@see
@Since
3.0.1
Arguments
[useDot=undefined]
(boolean): use dot prop or not
Returns
(DotProp): @chainable
Example
const chain = new Target()
chain.dot(false)
chain.set('moose.simple', 1)
toArr(chain.store.keys())
//=> ['moose.simple']
dot.dot.delete(obj=undefined, path=undefined)
Ⓢ Ⓣ
(Function): delete a path on an object
@extends
@Since
3.0.0
Arguments
obj=undefined
(Object): the object to DELETE the nested property from.path=undefined
(Array|Dottable|string): dot-prop-path to use
Returns
(void):
Example
dot.get({ a: { b: 2 } }, 'a.b') //=> 2
dot.get({ a: { b: 2 } }, ['a', 'b']) //=> 2
dot.get({ c: { b: 2 } }, ['a', 'b']) //=> undefined
dot.dot.get(obj=undefined, path=undefined, fallback=undefined)
Ⓢ Ⓣ
Function
@extends
@Since
3.0.0
Arguments
obj=undefined
(Object): the object to retrieve the nested property from.path=undefined
(Array|Dottable|string): dot-prop-path to usefallback=undefined
(*): use when there is no value at specified path
Returns
(*): value at path or fallback
Example
dot.get({ a: { b: 2 } }, 'a.b') //=> 2
dot.get({ a: { b: 2 } }, ['a', 'b']) //=> 2
dot.get({ c: { b: 2 } }, ['a', 'b']) //=> undefined
dot.dot.has(obj=undefined, path=undefined)
Ⓢ Ⓣ
Function
@extends
@Since
3.0.0
Arguments
obj=undefined
(Object): the object to retrieve the nested property from.path=undefined
(Array|Dottable|string): dot-prop-path to use
Returns
(boolean): has at path
Example
dot.has({ a: { b: 2 } }, 'a.b') //=> true
dot.has({ a: { b: 2 } }, ['a', 'b']) //=> true
dot.has({ c: { b: 2 } }, ['a', 'b']) //=> undefined
encase
encase.encase(call=undefined, [encaser=tryCatch])
Ⓢ Ⓣ
Function
@see
@symb
🛡
@Since
4.0.0
Arguments
call=undefined
(Function): function to encase[encaser=tryCatch]
(|Function): function to encase with
Returns
(Function): -> FunctionObject{onInvalid, onValid, rethrow, call}
Example
const throws = x => {
if (x === false) {
throw new Error('invalid - cannot be false')
}
return true
}
const api = encase(throws)
api.onValid(console.log)
api.onInvalid(console.error)
//--- invalid
api.call(false)
//=> 'invalid - cannot be false'
//--- valid
api.call(true)
//=> 'true'
encase.error$3(method=undefined, type=undefined)
Ⓢ Ⓣ
(Function): enhance an Error, enable rethrowing & better inspection
@see
@todos
- [ ] js stringify if development
@Since
4.0.0-alpha.1
Arguments
method=undefined
(Primitive): method being decoratedtype=undefined
(Type): type to validate with
Returns
(Function): function that returns a decorated TypeError with .inspect & metadata (arg, thrown, meta)
Example
const badValidator = x => {
if (x === 'bad') {
throw new Error('bad!')
}
}
const enhancer = enhanceError('eh', badValidator)
// called by plugins/encase when throws or invalid
let error
let arg = 'bad'
try {
error = badValidator(arg)
} catch (e) {
error = enhancer(arg, e, { metadata: true })
}
console.log(error)
//=> {[eh]: { type: badValidator, arg: 'bad', json, str, rethrow }}
//=> console.log on DEVELOPMENT
encase.tryCatch(call=undefined)
Ⓢ Ⓣ
Function
@see
@todos
- [ ] could curry
Arguments
call=undefined
(Function):
Returns
(*): validation/encased function call result
encase.withSpecification(specification=undefined, call=undefined, onInvalid=undefined, onInvalid=undefined)
Ⓢ Ⓣ
(Function): a special encased wrapper with no try catch but same api
@see
@Since
4.0.0
Arguments
specification=undefined
(Function): matchcall=undefined
(Function): cb to determine valid or invalidonInvalid=undefined
(Function): cb when invalidonInvalid=undefined
(Function): cb when valid
Returns
(Function): a lot of functions...
Example
const onInvalid = console.error
const onValid = console.debug
const onCall = console.log
const encased = withSpecification(x => true)(onCall)(onValid, onInvalid)
encased(1, 2, 3) //=> onCall (did not throw)
entries
entries(reduced=undefined)
Ⓢ Ⓣ
(Function): recursively reduce maps and objects that include reducable data
@see
@notes
- could curry, but this is super hot function
@sig
reduced => object => isMap(object) -> reduced; merge(object, reduced)
@Since
4.0.0
Arguments
reduced=undefined
(Object|any): merged object and reduced
Returns
(Function): Function(values: Object)
Example
const map = new Map()
map.set('eh', true)
const nested = new Map()
nested.set('reduced', true)
const chain = {
entries() {
return {
nested: reduce(nested),
key: true,
}
},
}
const reduced = reduce(map)
reduceEntries(reduced)({chain})
// => {
eh: true,
chain: {
nested: {
reduced: true,
key: true,
},
},
}
Example
const reducedIgnored = {
canada: {
store: chain,
},
}
const ignored = reduceEntries(reduced)(reducedIgnored)
//=> {
eh: true,
chain: {
nested: {
reduced: true,
},
key: true,
},
}
fp
fp._curryN(length=undefined, received=undefined, fn=undefined)
Ⓢ Ⓣ
(Function): Returns a curried equivalent of the provided function, with the specified arity. The curried function has two unusual capabilities. First, its arguments needn't be provided one at a time. If g
is R.curryN(3, f)
,
the following are equivalent:
g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
Secondly, the special placeholder value R.__
may be used to specify "gaps", allowing partial application of any combination of arguments, regardless of their positions. If g
is as
above and _
is R.__
, the following are equivalent:
g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
* g(_, 2)(_, 3)(1)
@see
@sig
Number -> ( -> a) -> ( -> a)
@Since
5.0.0-beta.1
Arguments
length=undefined
(Number): The arity of the curried function.received=undefined
(Array): An array of arguments received thus far.fn=undefined
(Function): The function to curry.
Returns
(Function): A new, curried function.
Example
var sumArgs = (...args) => R.sum(args)
var curriedAddFourNumbers = R.curryN(4, sumArgs)
var f = curriedAddFourNumbers(1, 2)
var g = f(3)
g(4) //=> 10
fp.curry(length=undefined, fn=undefined)
Ⓢ Ⓣ
(Function): Returns a curried equivalent of the provided function, with the specified arity. The curried function has two unusual capabilities. First, its arguments needn't be provided one at a time. If g
is R.curryN(3, f)
,
the following are equivalent:
g(1)(2)(3)
g(1)(2, 3)
g(1, 2)(3)
g(1, 2, 3)
Secondly, the special placeholder value R.__
may be used to specify "gaps", allowing partial application of any combination of arguments, regardless of their positions. If g
is as
above and _
is R.__
, the following are equivalent:
g(1, 2, 3)
g(_, 2, 3)(1)
g(_, _, 3)(1)(2)
g(_, _, 3)(1, 2)
g(_, 2)(1)(3)
g(_, 2)(1, 3)
* g(_, 2)(_, 3)(1)
@see
@sig
Number -> ( -> a) -> ( -> a)
@Since
v0.5.0
Arguments
length=undefined
(Number): The arity for the returned function.fn=undefined
(Function): The function to curry.
Returns
(Function): A new, curried function.
Example
var sumArgs = (...args) => R.sum(args)
var curriedAddFourNumbers = R.curryN(4, sumArgs)
var f = curriedAddFourNumbers(1, 2)
var g = f(3)
g(4) //=> 10
fp./* filename(value=undefined)
Ⓢ Ⓣ
(Function): Returns a function that always returns the given value. Note that for non-primitives the value returned is a reference to the original value.
This function is known as const
, constant
, or K
(for K combinator) in other languages and libraries.
@see
@sig
a -> (* -> a)
@Since
v5.0.0
Arguments
value=undefined
(*): The value to wrap in a function
Returns
(Function): A Function :: * -> val.
Example
var t = always('Tee')
t() //=> 'Tee'
fp.prop(p=undefined, obj=undefined)
Ⓢ Ⓣ
(Function): Returns a function that when supplied an object returns the indicated property of that object, if it exists.
@sig
s -> {s: a} -> a | Undefined
@Since
v5.0.0
Arguments
p=undefined
(String): The property nameobj=undefined
(Object): The object to query
Returns
(*): The value at obj.p
.
Example
R.prop('x', { x: 100 }) //=> 100
R.prop('x', {}) //=> undefined
fp.constructN(n=undefined, Klass=undefined)
Ⓢ Ⓣ
(Function): Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. The arity of the function returned is specified to allow using variadic constructor functions.
@see
@sig
Number -> ( -> {}) -> ( -> {})
@symb
👷
@extends
- undefined
- undefined
@Since
5.0.0-beta.4
Arguments
n=undefined
(number): The arity of the constructor function. *(aka, number of args)*Klass=undefined
(Function): The constructor function to wrap. *(class to donew Klass
on)*
Returns
(Function): A wrapped, curried constructor function.
Example
// Variadic Constructor function
function Salad() {
this.ingredients = arguments
}
Salad.prototype.recipe = function() {
var instructions = R.map(
ingredient => 'Add a dollop of ' + ingredient,
this.ingredients
)
return R.join('\n', instructions)
}
var ThreeLayerSalad = R.constructN(3, Salad)
// Notice we no longer need the 'new' keyword, and the constructor is curried for 3 arguments.
var salad = ThreeLayerSalad('Mayonnaise')('Potato Chips')('Ketchup')
console.log(salad.recipe())
// Add a dollop of Mayonnaise
// Add a dollop of Potato Chips
// Add a dollop of Ketchup
fp.replace(pattern=undefined, replacement=undefined, str=undefined)
Ⓢ Ⓣ
(Function): Replace a substring or regex match in a string with a replacement.
@see
@sig
RegExp|String -> String -> String -> String
@Since
v5.0.0
Arguments
pattern=undefined
(RegExp|String): A regular expression or a substring to match.replacement=undefined
(String): The string to replace the matches with.str=undefined
(String): The String to do the search and replacement in.
Returns
(String): The result.
Example
replace('foo', 'bar', 'foo foo foo') //=> 'bar foo foo'
replace(/foo/, 'bar', 'foo foo foo') //=> 'bar foo foo'
// Use the "g" (global) flag to replace all occurrences:
replace(/foo/g, 'bar', 'foo foo foo') //=> 'bar bar bar'
fp.pipeTwo(f=undefined, g=undefined)
Ⓢ Ⓣ
(Function): Performs left-to-right function composition. ONLY CAN PIPE 2
ARGUMENTS
@see
- https://github.com/ramda/ramda/blob/master/src/pipe.js
- https://github.com/ramda/ramda/blob/master/test/pipe.js
@notes
- The result of pipe is not automatically curried.
- This is a variation, is the internal version with only 2 functions, for now
@Since
v5.0.0
Arguments
f=undefined
(...Function): function firstg=undefined
(...Function): function next
Returns
(Function):
Example
var f = R.pipe(Math.pow, R.negate)
f(3, 4) // -(3^4) + 1
fp.pipe(first=undefined, rest=undefined)
Ⓢ Ⓣ
(Function): Performs left-to-right function composition. The leftmost function may have any arity; the remaining functions must be unary. In some libraries this function is named sequence
.
@see
- R.compose
- https://github.com/ramda/ramda/blob/master/src/pipe.js
- https://github.com/ramda/ramda/blob/master/test/pipe.js
@sig
(((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> ((a, b, ..., n) -> z)
@symb
R.pipe(f, g, h)(a, b) = h(g(f(a, b)))
@extends
@Since
v5.0.0
Arguments
first=undefined
(Function): function firstrest=undefined
(...Function): function next
Returns
(Function):
Example
var f = R.pipe(Math.pow, R.negate, R.inc)
f(3, 4) // -(3^4) + 1
Example
var x = v => v + 'x'
var y = v => v + 'y'
var z = v => v + 'z'
const xyz = pipe(x, y, z)
/// starts with w, adds x, then y, then z
const wxyz = xyz('w')
//=> 'wxyz'
fp.arity(n=undefined, fn=undefined)
Ⓢ Ⓣ
(Function): just for .length
of a function?
@see
@todos
- [ ] keeping this means change uglify...
@Since
5.0.0
Arguments
n=undefined
(number): number of argumentsfn=undefined
(Function): function to wrap
Returns
(Function): function with params
Example
const wan = one => console.log(one)
arity(1, wan)
=> function(one => wan(one))
fp.mapWhere(obj=undefined, predicate=undefined)
Ⓢ Ⓣ
(Function): Creates an array of values by running each property of object
thru
iteratee
. The iteratee is invoked with three arguments: (value, key, object).
@see
@Since
5.0.0
Arguments
obj=undefined
(Object): The object to iterate over.predicate=undefined
(Function): The function invoked per iteration.
Returns
(Array): Returns the new mapped array.
Example
const square = n => n * n
map({ a: 4, b: 8 }, square)
// => [16, 64] (iteration order is not guaranteed)
from
get
getMeta
has
has(key=undefined, [prop=undefined])
Ⓢ Ⓣ
Function
@Since
4.0.0
Arguments
key=undefined
(Primitive):[prop=undefined]
(|Primitive):
Returns
(boolean):
if
includes
includes.includes(haystack=undefined, needle=undefined)
Ⓢ Ⓣ
Function
@see
@todos
- [ ]
~haystack.indexOf(needle)
Arguments
haystack=undefined
(Array|string): haystack includes needleneedle=undefined
(*|string): needle in haystack
Returns
(boolean): needle in haystack
Example
includes('eh', 'e') //=> true
includes('eh', 'nope') //=> false
includes(['eh'], 'eh') //=> true
includes(['eh'], 'nope') //=> false
index
is
is.empty(x=undefined)
Ⓢ Ⓣ
(Function): Returns true
if the given value is its type's empty value;
false
otherwise.
@see
@sig
a -> Boolean
@Since
v0.1.0
Arguments
x=undefined
(*): value to check if empty
Returns
(boolean):
Example
isEmpty([1, 2, 3]) //=> false
isEmpty([]) //=> true
isEmpty('') //=> true
isEmpty(null) //=> false
isEmpty({}) //=> true
isEmpty({ length: 0 }) //=> false
is.arrayOf(predicate=undefined)
Ⓢ Ⓣ
(Function): every item in an array matches predicate
@Since
4.0.0 was in validatorBuilder
Arguments
predicate=undefined
(Function): test to pass on every item in an array
Returns
(boolean): all match predicate
Example
isArrayOf(isTrue)([true, true]) //=> true
isArrayOf(isEmpty)(['']) //=> true
isArrayOf(isBoolean)([true, false, 1, 2, 0]) //=> false
isArrayOf(isString)(['string', Number]) //=> false
is.exports(obj=undefined)
Ⓢ Ⓣ
(Function): The base implementation of getTag
without fallbacks for buggy environments.
@see
- https://github.com/lodash/lodash/blob/master/.internal/baseGetTag.js
- https://github.com/jonschlinkert/kind-of
- https://github.com/substack/js-traverse/blob/master/index.js#L285
- http://luxiyalu.com/object-prototype-tostring-call/
@todos
- [ ] obj[Symbol.toStringTag]
- [ ] run deopt check on this invoking see how many invocations... are needed to inline
@Since
3.0.0
Arguments
obj=undefined
(*): The value toObject.prototype.toString.call(obj)
.
Returns
(string): Returns the toStringTag
.
Example
toS({})
//=> '[object Object]'
toS(function() {})
//=> '[Object Function]'
getTag([])
//=> '[object Array]'
is.hasIn(obj=undefined, prop=undefined)
Ⓢ Ⓣ
(Function): isIn, but first checks it is not null
@extends
- undefined
- undefined
@Since
5.0.0
Arguments
obj=undefined
(Object): object to checkprop=undefined
(any): property to check in object
Returns
(boolean):
Example
hasIn({}, 'eh') //=> false
hasIn(null, 'eh') //=> false
hasIn({ eh: true }, 'eh') //=> true
is.isArray(arg=undefined)
Ⓢ Ⓣ
Function
@see
@todos
@Since
3.0.0
Arguments
arg=undefined
(*):
Returns
(boolean): isArray(arg)
is.async(x=undefined)
Ⓢ Ⓣ
Function
@see
@Since
4.0.0-beta.2
Arguments
x=undefined
(*): value
Returns
(boolean): isAsync
Example
isAsync(async function() {})
//=> true
isAsync(new Promise(r => r()))
//=> false
isAsync({})
//=> false
isAsync(function() {})
is.isAsyncish(x=undefined)
Ⓢ Ⓣ
(Function): async function or promise
@extends
- undefined
- undefined
@Since
4.0.0-beta.2
Arguments
x=undefined
(*): value
Returns
(boolean): x isAsyncish
Example
isAsyncish(async function() {}) //=> true
isAsyncish(new Promise(r => r())) //=> true
isAsyncish({}) //=> false
isAsyncish(function() {}) //=> false
is.boolean_1(x=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is classified as a boolean primitive OR object.
@see
@extends
- undefined
- undefined
- undefined
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isBoolean
Example
isBoolean(false)
//=> true
isBoolean(new Boolean(1))
//=> true
isBoolean(1)
//=> false
isBoolean('')
//=> false
is.booleanPrimitive(x=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is classified as a boolean primitive NOT object.
@see
@notes
- could also have typeof x === 'boolean' || (/true|false/).test(x)
@extends
- undefined
- undefined
@Since
5.0.0-beta.4
Arguments
x=undefined
(*): value
Returns
(boolean): isBooleanPrimitive
Example
isBooleanPrimitive(false)
//=> true
isBooleanPrimitive(new Boolean(1))
//=> false
isBooleanPrimitive(1)
//=> false
isBooleanPrimitive('')
//=> false
is.date(x=undefined)
Ⓢ Ⓣ
Function
@extends
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isDate
Example
isDate(new Date())
//=> true
isDate(Date.now())
//=> false
isDate(1)
//=> false
isDate('')
//=> false
Example
const e = {}
eh[Symbol.toStringTag] = '[Object Date]'
isDate(eh)
//=> true
Example
class Eh extends Date()
isDate(new Eh())
//=> true
is.isDot(x=undefined)
Ⓢ Ⓣ
Function
@see
@todos
- [ ] update with conditional
@Since
3.0.0
Arguments
x=undefined
(*): value to check
Returns
(boolean): x isDot
Example
isDot('eh.oh') //=> true
isDot('eh') //=> false
isDot(['eh', 'oh']) //=> true
is.isEnumerable(obj=undefined, prop=undefined)
Ⓢ Ⓣ
(Function): object at property is enumerable
@see
@todos
- [ ] use fp/call
@Since
3.0.0
Arguments
obj=undefined
(*|Object):prop=undefined
(*|string):
Returns
(boolean): obj[prop] is enumerable
Example
const obj = { eh: true }
isEnumerable(obj, 'eh')
//=> true
const objPropEnumerable = isEnumerable(obj)
objPropEnumerable('eh')
//=> true
Object.defineProperty(obj, 'length', {
enumerable: false,
value: () => Object.keys(obj).length,
})
isEnumerable(obj, 'length')
//=> false
is.error$1(x=undefined)
Ⓢ Ⓣ
Function
@Since
4.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isError
Example
isError(new Error())
//=> true
isError(new Error().stack)
//=> false
isError(1)
//=> false
isError('')
//=> false
Example
const e = {}
eh[Symbol.toStringTag] = '[Object Error]'
isError(eh)
//=> true
Example
class Eh extends Error()
isError(new Eh())
//=> true
is._false(x=undefined)
Ⓢ Ⓣ
Function
@Since
4.0.0-alpha.1
Arguments
x=undefined
(*): value
Returns
(boolean): isFalse
Example
isFalse(false)
//=> true
isFalse(true)
//=> false
isFalse(0)
//=> false
isFalse('')
//=> false
is._function(x=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is classified as a Function
object.
@see
@notes
- || x instanceof Function
@Since
3.0.0
Arguments
x=undefined
(*): The value to check.
Returns
(boolean): x isFunction
Example
isFunction(function() {})
//=> true
isFunction(() => {})
//=> true
isFunction(new Function())
//=> true
isFunction(1)
//=> false
isFunction('')
//=> false
isFunction(/abc/)
// => false
is.isIn(obj=undefined, prop=undefined)
Ⓢ Ⓣ
(Function): prop is in Object(obj)
@Since
5.0.0
Arguments
obj=undefined
(Object): object to check property ofprop=undefined
(Primitive): property in obj
Returns
(boolean): property
Example
isIn({ eh: true }, 'eh') //=> true
isIn({ eh: true }, 'oh') //=> false
is.(x=undefined)
Ⓢ Ⓣ
Function
@see
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isIterator
Example
isIterator(new Set().values())
//=> true
isIterator(new Map.entries())
//=> true
isIterator(new Map())
//=> false
isIterator('')
//=> false
isIterator(1)
//=> false
Example
const e = {}
eh[Symbol.toStringTag] = '[Map Iterator]'
isIterator(eh)
//=> true
eh[Symbol.toStringTag] = '[Set Iterator]'
isIterator(eh)
//=> true
Example
class Eh extends Set()
isIterator(new Eh().values())
//=> true
is.map(x=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is classified as a Map
object.
@see
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isMap
Example
isMap(new Map())
//=> true
isMap(new Map.entries())
//=> false
isMap(new Set())
//=> false
isMap({})
//=> false
isMap('')
//=> false
isMap(1)
//=> false
isMap(new WeakMap())
// => false
Example
const e = {}
eh[Symbol.toStringTag] = '[object Map]'
isMap(eh)
Example
class Eh extends Map()
isMap(new Eh())
//=> true
is.mapish(x=undefined)
Ⓢ Ⓣ
Function
@extends
@Since
3.0.0
Arguments
x=undefined
(*): value to check
Returns
(boolean): isMapish
Example
isMapish(new Map())
//=> true
isMapish(new Chain())
//=> true
isMapish({})
//=> false
isMapish(1)
//=> false
is.matcher(x=undefined)
Ⓢ Ⓣ
Function
@see
@Since
3.0.0
Arguments
x=undefined
(*): value to check
Returns
(boolean): isFunction || isRegExp
Example
isMatcher(/(.*)/)
//=> true
isMatcher(x => true)
//=> true
isMatcher(1)
//=> false
isMatcher('.*')
//=> false
is._null(x=undefined)
Ⓢ Ⓣ
Function
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isNull
Example
isNull(null)
//=> true
isNull(undefined)
//=> false
isNull(void 0)
//=> false
isNull({})
//=> false
isNull('')
//=> false
isNull(1)
//=> false
is.nullOrUndefined(x=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is null
or undefined
.
@see
- is/null
- is/undefined
- https://github.com/infernojs/inferno/blob/master/packages/inferno-shared/src/index.ts#L23
@Since
4.0.0-alpha.1
Arguments
x=undefined
(*): value
Returns
(boolean): isNullOrUndefined
Example
isNullOrUndefined(null)
//=> true
isNullOrUndefined(undefined)
//=> true
isNullOrUndefined(void 0)
//=> true
isNullOrUndefined(NaN)
//=> false
isNullOrUndefined({})
//=> false
isNullOrUndefined('')
//=> false
isNullOrUndefined(1)
//=> false
isNullOrUndefined(false)
//=> false
is.number(x=undefined)
Ⓢ Ⓣ
Function
@see
@notes
- was not needed except for abstract == const isObj = require('./obj') const isSymbol = require('./symbol') (isObj(x) || isSymbol(x) ? false : (/^0x[0-9a-f]+$/i).test(x) ||
(/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x))
@extends
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isNumber
Example
isNumber(1)
//=> true
isNumber(new Number(1))
//=> true
isNumber(Number(1))
//=> true
isNumber(NaN)
//=> true
isNumber(null)
//=> false
isNumber(undefined)
//=> false
isNumber(void 0)
//=> false
isNumber({})
//=> false
isNumber('')
//=> false
isNumber(false)
//=> false
is.numberPrimitive(x=undefined)
Ⓢ Ⓣ
Function
@see
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isNumberPrimitive
Example
isNumberPrimitive(1)
//=> true
isNumberPrimitive(Number(1))
//=> true
isNumberPrimitive(NaN)
//=> true
isNumberPrimitive(new Number(1))
//=> false
isNumberPrimitive(null)
//=> false
isNumberPrimitive(undefined)
//=> false
isNumberPrimitive(void 0)
//=> false
isNumberPrimitive({})
//=> false
isNumberPrimitive('')
//=> false
isNumberPrimitive(false)
//=> false
is.obj(value=undefined)
Ⓢ Ⓣ
Function
@see
- http://stackoverflow.com/questions/34111902/why-do-lodashs-isobject-isplainobject-behave-differently-than-typeof-x
- https://github.com/lodash/lodash/blob/master/isObject.js
@notes
- Object.prototype.toString.call(val) === '[object Object]'
@Since
3.0.0
Arguments
value=undefined
(*): The value to check.
Returns
(boolean): Returns true
if value
is an object, else false
.
Example
isObject({})
// => true
isObject([1, 2, 3])
// => true
isObject(Function)
// => true
isObject(null)
// => false
is.objTypeof(x=undefined)
Ⓢ Ⓣ
Function
@see
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isObjLoose
Example
isObjLoose(new Object())
//=> true
isObjLoose({})
//=> true
isObjLoose(Object.create(null))
//=> true
isObjLoose(null)
//=> true
isObjLoose(new Set())
//=> false
isObjLoose(function() {})
//=> false
isObjLoose('')
//=> false
isObjLoose(1)
//=> false
is.objNotNull(x=undefined)
Ⓢ Ⓣ
Function
@see
@todos
- [ ] !Array.isArray
@extends
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isObjNotNull
Example
isObjNotNull(new Object())
//=> true
isObjNotNull({})
//=> true
isObjNotNull(Object.create(null))
//=> true
isObjNotNull(null)
//=> false
isObjNotNull(new Set())
//=> false
isObjNotNull(function() {})
//=> false
isObjNotNull('')
//=> false
isObjNotNull(1)
//=> false
is.isObjPure(x=undefined)
Ⓢ Ⓣ
Function
@extends
- undefined
- undefined
- undefined
- undefined
@Since
3.0.0
Arguments
x=undefined
(*): value to check
Returns
(boolean): is obj & !null & !undefined & !array & !function
Example
isObjPure(function() {})
//=> false
isObjPure(null)
//=> false
isObjPure([])
//=> false
isObjPure({})
//=> true
is.objWithKeys(x=undefined)
Ⓢ Ⓣ
Function
@see
@todos
- [ ] @NOTE need to be more careful, needs to check for vanilla objects, not native ones since e.g. Error has no keys
@extends
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isObjWithKeys
Example
isObjWithKeys({ eh: true })
//=> true
isObjWithKeys({})
//=> false
isObjWithKeys(new Object())
//=> false
isObjWithKeys(Object.create(null))
//=> false
isObjWithKeys(null)
//=> false
isObjWithKeys(new Set())
//=> false
isObjWithKeys(function() {})
//=> false
isObjWithKeys('')
//=> false
isObjWithKeys(1)
//=> false
is.promise(x=undefined)
Ⓢ Ⓣ
(Function): is a Promise
@see
- https://github.com/jonschlinkert/kind-of/blob/master/index.js#L66
- https://github.com/sindresorhus/promise-fun
@Since
4.0.0-beta.2
Arguments
x=undefined
(*): value
Returns
(boolean): x isPromise
Example
isPromise(new Promise(r => r))
//=> true
isPromise(async function() {})
//=> false // on some environments, true
isPromise({})
//=> false
isPromise(Object.create(null))
//=> false
isPromise(null)
//=> false
isPromise(new Set())
//=> false
isPromise(function() {})
//=> false
isPromise('')
//=> false
isPromise(1)
//=> false
is.isPrototypeOf(haystack=undefined, needle=undefined)
Ⓢ Ⓣ
(Function): check if arg 1
is prototype of arg 2
@see
@todos
- [ ] curry2
@Since
3.0.0
Arguments
haystack=undefined
(*|Object): check needle againstneedle=undefined
(*|Object): is prototype of haystack
Returns
(boolean): needle isPrototypeOf haystack
Example
class Eh extends Function {}
class Canada extends Eh {}
isPrototypeOf(Eh, Function) //=> true
isPrototypeOf(Canada, Function) //=> true
isPrototypeOf(Eh, Date) //=> false
isPrototypeOf({}, Object) //=> true
isPrototypeOf({}, Array) //=> false
is.real(x=undefined)
Ⓢ Ⓣ
Function
@see
- is/null
- is/undefined
- http://2ality.com/2013/04/quirk-implicit-conversion.html
- https://javascriptrefined.io/nan-and-typeof-36cd6e2a4e43
- https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
@notes
- eslint-disable-next-line no-self-compare
&& x !== x
@extends
@Since
3.0.0
Arguments
x=undefined
(*): value
Returns
(boolean): isReal
Example
isReal(null)
//=> false
isReal(void 0)
//=> false
const nan = Number(undefined)
isReal(nan)
//=> false
isReal({ eh: true })
//=> true
isReal({})
//=> true
isReal(Object)
//=> true
isReal([])
//=> true
isReal(new Set())
//=> true
isReal(function() {})
//=> true
isReal('')
//=> true
isReal(1)
//=> true
is._true(x=undefined)
Ⓢ Ⓣ
Function
@Since
4.0.0-alpha.1
Arguments
x=undefined
(*): value
Returns
(boolean): isTrue
Example
isTrue(true)
//=> true
isTrue(false)
//=> false
isTrue(1)
//=> false
isTrue('')
//=> false
is._undefined(x=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is undefined
.
@see
- is/nullOrUndefined
- https://github.com/infernojs/inferno/blob/master/packages/inferno-shared/src/index.ts#L57
@Since
4.0.0-alpha.1
Arguments
x=undefined
(*): value
Returns
(boolean): isUndefined
Example
isUndefined(undefined)
//=> true
isUndefined(void 0)
//=> true
isUndefined(null)
//=> false
isUndefined(NaN)
//=> false
isUndefined({})
//=> false
isUndefined('')
//=> false
isUndefined(1)
//=> false
isUndefined(false)
//=> false
is.primitive$2(x=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is classified as a primitive
(number|string|boolean|null|undefined)
@see
- http://www.adequatelygood.com/Object-to-Primitive-Conversions-in-JavaScript.html
- https://developer.mozilla.org/en-US/docs/Glossary/Primitive
- http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
@Since
4.0.0 was in another file
Arguments
x=undefined
(*): The value to check.
Returns
(boolean): x is number|string|boolean|null|undefined
Example
isPrimitive('abc') // => true
isPrimitive(1) // => true
isPrimitive('') // => true
isPrimitive(null) // => true
isPrimitive(undefined) // => true
isPrimitive(void 0) // => true
isPrimitive(new String('abc')) // => false
isPrimitive([]) // => false
isPrimitive(() => {}) // => false
isPrimitive({}) // => false
is.string(x=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is classified as a String
primitive or object.
@see
- https://github.com/lodash/lodash/blob/master/isString.js
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
- isStringPrimitive
@extends
@Since
3.0.0
Arguments
x=undefined
(*): The value to check.
Returns
(boolean): Returns true
if value
is a string, else false
.
Example
isString('abc')
// => true
isString(new String('abc'))
// => true
isString(1)
// => false
is.stringOrNumber(x=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is classified as a String
primitive or object.
@see
- https://github.com/infernojs/inferno/blob/master/packages/inferno-shared/src/index.ts#L23
- https://github.com/lodash/lodash/blob/master/isString.js
@Since
3.0.0
Arguments
x=undefined
(*): The value to check.
Returns
(boolean): Returns true
if value
is a string, else false
.
Example
isString('abc')
// => true
isString(1)
// => false
is.stringPrimitive(x=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is classified as a String
primitive.
@see
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
- https://github.com/lodash/lodash/blob/master/isString.js
- is/string
@Since
3.0.0
Arguments
x=undefined
(*): The value to check.
Returns
(boolean): Returns true
if value
is a string, else false
.
Example
isString('abc')
// => true
isString(new String('abc'))
// => false
isString(1)
// => false
is.symbol(value=undefined)
Ⓢ Ⓣ
(Function): Checks if value
is classified as a Symbol
primitive or object.
@Since
4.0.0
Arguments
value=undefined
(*): The value to check.
Returns
(boolean): Returns true
if value
is a symbol, else false
.
Example
isSymbol(Symbol.iterator)
// => true
isSymbol('abc')
// => false
is.index$12
isNotRealOrIsEmpty
iteratable
iteratable(x=undefined)
Ⓢ Ⓣ
(Function): is able to be iterated on
@extends
- undefined
- undefined
- undefined
- undefined
- undefined
- undefined
- undefined
- undefined
Arguments
x=undefined
(*): node is iteratable
Returns
(boolean): x isIteratable
Example
isIteratable([]) //=> true
isIteratable({}) //=> true
isIteratable(new Date()) //=> false
isIteratable(Symbol('eh')) //=> false
isIteratable(new Promise(r => r())) //=> false
isIteratable(new Error('eh')) //=> false
keysObjOrArray
keysObjOrArray(obj=undefined)
Ⓢ Ⓣ
(Function): Creates an array of the own enumerable property names of object
.
Note: Non-object values are coerced to objects. See the
ES spec for more details.
@see
@todos
@Since
0.1.0
Arguments
obj=undefined
(Object): The object to query.
Returns
(Array): Returns the array of property names.
Example
function Foo() {
this.a = 1
this.b = 2
}
Foo.prototype.c = 3
keys(new Foo())
// => ['a', 'b'] (iteration order is not guaranteed)
keys('hi')
// => ['0', '1']
lengthFromZero
lengthFromZero(obj=undefined)
Ⓢ Ⓣ
(Function): when length > 1
, use length-1 otherwise, when length == 1
, use 0
default, use length
@todos
- [ ] lense to use an object, or transform it to one with .length? const len = prop('length') // when isObj, use len, otherwise, value const coerceLength = lense([isObj, len])
Arguments
obj=undefined
(Array|Object|number): with length
Returns
(number): obj length from 0
Example
lengthFromZero([1]) //=> 1
lengthFromZero([]) //=> 0
lengthFromZero([1, 2, 3]) //=> 2
markForGarbageCollection
markForGarbageCollection(obj=undefined)
Ⓢ Ⓣ
(Function): remove all methods, mark for garbage collection
@see
- https://stackoverflow.com/questions/1947995/when-should-i-use-delete-vs-setting-elements-to-null-in-javascript
- https://v8project.blogspot.ca/2015/08/getting-garbage-collection-for-free.html
- https://github.com/natewatson999/js-gc
- https://github.com/siddMahen/node-gc
- http://buildnewgames.com/garbage-collector-friendly-code/
- https://stackoverflow.com/questions/27597335/ensuring-object-can-be-garbage-collected
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
@todos
- [ ] blacklist = [] param
- [ ] put all GC events into a cached map and debounce the operation
@Since
4.0.0
Arguments
obj=undefined
(Object): object to traverse and clear
Returns
(void):
Example
var scoped = {}
var ref = () => scoped
var obj = { scoped, ref, eh: true }
markForGarbageCollection(obj)
//=> void
obj
//=> undefined|{}
matcher
matcher.escapeStringRegex(str=undefined)
Ⓢ Ⓣ
Function
@see
@notes
- also as const escapeStringRegexp = require('escape-string-regexp');
@Since
3.0.0
Arguments
str=undefined
(string): string to escape
Returns
(string): escaped string
Example
const escaped = escapeStringRegexp('how much $ for a unicorn?')
//=> 'how much \$ for a unicorn\?'
new RegExp(escaped)
matcher.make(pattern=undefined, shouldNegate=undefined, alphaOmega=undefined)
Ⓢ Ⓣ
(Function): turn any string[], function[], or RegExp[] into a matcher
@Since
3.0.0
Arguments
pattern=undefined
(Function|RegExp|string|string[]): a matchable patternshouldNegate=undefined
(|boolean): turn into a negated regexalphaOmega=undefined
(|boolean): should have regex start at the beginning and the end
Returns
(*): matchable
Example
matcher.make('*')
//=> RegExp('.*', 'i')
Example
var any = new RgExp('.*', 'i')
matcher.make(any)
//=> any
Example
var strings = x => typeof x === 'string'
matcher.make(strings)
// {test: strings}
Example
var tester = { test: x => x === true }
matcher.make(tester)
// tester
Example
var noName = '!name'
matcher.make(noName, true)
// new RegExp('(?:name)', 'i')
Example
var noName = '!name'
matcher.make(noName, true, true)
// new RegExp('^(?:name)$', 'i')
matcher.matcher(inputs=undefined, patterns=undefined, shouldNegate=undefined, alphaOmega=undefined)
Ⓢ Ⓣ
(Function): same as .make but also accepts inputs, and returns an array
@see
@Since
3.0.0
Arguments
inputs=undefined
(string|string[]): input to use patterns as predicates onpatterns=undefined
(Function|RegExp|string|string[]): predicates to match with, transformed to MatchershouldNegate=undefined
(|boolean): should negate, passed to matcher.makealphaOmega=undefined
(|boolean): should enforce regex @beginning and end, passed to .matcher
Returns
(*):
Example
matcher(['foo', 'bar', 'moo'], ['*oo', '!foo'])
//=> ['moo']
matcher(['foo', 'bar', 'moo'], ['!*oo'])
Example
matcher('kinga', 'kinga')
//=> ['kinga']
matcher('k*nga', 'kinga')
//=> ['kinga']
matcher('kinga', 'nope')
//=> []
matcher(new RegExp(/kinga/), 'kinga')
//=> ['kinga']
matcher(new RegExp(/kinga/), 'nope')
//=> ['nope']
matcher(x => x === 'kinga', 'kinga')
//=> ['kinga']
matcher(x => x === 'kinga', 'nope')
//=> []
matcher({ test: x => x === 'kinga' }, 'kinga')
//=> ['kinga']
matcher({ test: x => x === 'kinga' }, 'nope')
//=> []
merge
merge([obj2=undefined])
Ⓢ Ⓣ
(Function): merges object in, goes through all keys, checks cbs, dopemerges
@see
@todos
- [ ] issue here if we extend without shorthands &
we want to merge existing values... :s
@Since
1.0.0
Arguments
[obj2=undefined]
(Object): object to merge in, defaults to this.get('obj')
Returns
(MergeChain): @chainable
Example
const chain = new Chain()
chain.merge({ canada: { eh: true } })
chain.merge({ canada: { arr: [0, { '1': 2 }], eh: { again: true } } })
chain.entries()
//=> {canada:{ eh: {again: true}, arr: [0, {'1': 2}] }}
merge(obj=undefined, [handleMergeFn=undefined])
Ⓢ Ⓣ
(Function): merges an object with the current store
@see
@todos
- [ ] needs to pass in additional opts somehow...
@Since
0.4.0
Arguments
obj=undefined
(Object): object to merge[handleMergeFn=undefined]
(|Function): return the merger to the callback
Returns
(ChainedMap): @chainable
Example
const chain = new Chain()
chain.set('eh', [1])
chain.merge({ eh: [2] })
chain.get('eh')
// => [1, 2]
Example
const chain = new Chain()
chain.set('emptyArr', [])
chain.merge({emptyArr: []}, mergeChain =>
mergeChain.onExisting((a, b) => []).merger((a, b) => []).merge()
)
chain.get('emptyArr').length)
//=> 0
meta
meta(key=undefined, [prop=undefined], [value=undefined])
Ⓢ Ⓣ
(Function): a single easily minifiable function, dynamically setting & getting depending on arguments to avoid nested property accessing only instantiating when values are addded
@Since
4.0.0
Arguments
key=undefined
(Primitive):[prop=undefined]
(|Primitive):[value=undefined]
(|any): *(when no value, it's a getter)*
Returns
(*): depending on args
method
method(names=undefined)
Ⓢ Ⓣ
(Function): the way to easily start building methods when using chainable instances
@see
@Since
4.0.0
Arguments
names=undefined
(Primitive|string|string[]): method names to add to the object
Returns
(MethodChain): @chainable
Example
const chain = new Chain()
chain.method('eh').build()
chain.eh(true)
chain.get('eh')
// => true
methodEncasingFactory
methodEncasingFactory(name=undefined, parent=undefined, built=undefined)
Ⓢ Ⓣ
(Function): 3 steps
- enhance error
- encase function with a specification
- build a function to call onInvalid or onInvalid depending
@symb
⛑🏭
@Since
4.0.0
Arguments
name=undefined
(string): name of the methodparent=undefined
(Function|Object): object being decorated by MethodChainbuilt=undefined
(Object): the current state of the decoration
Returns
(Function): curried finisher, for specification
Example
methodEncasingFactory('eh', {}, { onSet: console.log })
//=> Function
notNested
paths
paths(key=undefined, value=undefined, [longest=undefined])
Ⓢ Ⓣ
(Function): gathers dot.prop from any value, with a prefixed/base key
@see
@notes
- had
onlyLongest
&asString
but can just .join(',') to match
@todos
- [ ] should build a trie if doing this
@Since
4.0.0
Arguments
key=undefined
(Primitive): prefixing key for the paths, root path/keyvalue=undefined
(Traversable): traversable value to extract paths from[longest=undefined]
(|boolean): optionally filter to keep only longest/deepest paths
Returns
(*): paths[]
Example
dotPropPaths('', { oh: { eh: true } })
//=> ['oh.eh']
dotPropPaths('moose', { oh: { eh: true } })
//=> ['moose.oh.eh']
pooler
pooler.addPoolingTo(CopyConstructor=undefined, pooler=undefined)
Ⓢ Ⓣ
(Function): Augments CopyConstructor
to be a poolable class, augmenting only the class itself (statically) not adding any prototypical fields. Any CopyConstructor you give this may have a poolSize
property,
and will look for a prototypical destructor
on instances.
@Since
5.0.0
Arguments
CopyConstructor=undefined
(Function|Object): Constructor that can be used to reset.pooler=undefined
(Function): Customizable pooler.
Returns
(Object): enhanced constructor, decorated with pooler
Example
class Eh {}
addPoolingTo(Eh) // can optionally pass in pooler as second arg
//=> Eh.instancePool = []
//=> Eh.getPooled = pooler || singleArgumentPooler
//=> Eh.poolSize = 10
//=> Eh.release = standardReleaser
pooler.oneArgumentPooler(copyFieldsFrom=undefined)
Ⓢ Ⓣ
(Function): Static poolers. Several custom versions for each potential number of arguments. A completely generic pooler is easy to implement, but would require accessing the arguments
object. In each of these, this
refers to the Class itself, not an instance. If any others are needed, simply add them here, or in their own files.
@Since
5.0.0
Arguments
copyFieldsFrom=undefined
(Object): obj with instance pool
Returns
(Object): instance of Klass
Example
class Eh {}
addPoolingTo(Eh)
const eh = Eh.getPooled() //=> oneArgumentPooler(Eh)
eh.release()
pooler.// const pooler
reduce
reduce(map=undefined)
Ⓢ Ⓣ
(Function): Map -> Object
@see
@Since
4.0.0
Arguments
map=undefined
(Map): map to reduce, calls entries, turns into an array, then object
Returns
(Object): reduced object
Example
var emptyMap = new Map()
reduce(emptyMap)
// => {}
Example
var map = new Map()
map.set('eh', 1)
reduce(map)
// => {eh: 1}
reduce.clean(obj=undefined)
Ⓢ Ⓣ
(Function): goes through the maps, and the map values, reduces them to array then to an object using the reduced values
@see
@todos
- [ ] seems to be overkill with reducing mapping just copy & ignore or delete?
Arguments
obj=undefined
(Object): object to clean, usually .entries()
Returns
(Object): reduced object, without notReal
values
Example
const map = new ChainedMap()
map
.set('emptyArr', [])
.set('arr', [1])
.set('nill', null)
.set('emptyObj', {})
.set('obj', { keys: true })
clean(map.entries())
//=> {arr: [1], obj: {keys: true}}
regexp
schema
schema(obj=undefined)
Ⓢ Ⓣ
(Function): handles:
1. recursively building nestable schemas, 2. creating MethodChains for all types 3. carrying over the inheritable properties 4. @modifies @injects @decorates .add(customValidators)
Arguments
obj=undefined
(Schema):
Returns
(MethodFactory): @chainable
schema.typeListFactory(fullKey=undefined)
Ⓢ Ⓣ
Function
Arguments
fullKey=undefined
(string): a key with|
and/or '&'
Returns
(Function): validator
Example
const isStringOrNumber = typeListFactory('string|number')
isStringOrNumber(1)
//=> true
isStringOrNumber('one')
//=> true
isStringOrNumber(Object)
//=> false
schema.typeValidator(input=undefined)
Ⓢ Ⓣ
(Function): build a recursive schema for all around runtime type safety
@see
@symb
🛂
@Since
4.0.0-beta.1
Arguments
input=undefined
(any): the input to validate
Returns
(boolean): valid
Example
const typeValidator = schemaFactory('eh', x => typeof x === 'string')
var isValid = typeValidator('stringy')
//=> true
var isValid = typeValidator(Number)
//=> false
Example
const isNumber = x => typeof x === 'number'
const typeValidator = schemaFactory('eh', { canada: 'number' })
var isValid = typeValidator({ canada: 1 })
//=> true
var isValid = typeValidator({})
//=> false
var isValid = typeValidator({ canada: false })
//=> false
var isValid = typeValidator(1)
//=> false
schemaFactory
schemaFactory(property=undefined, nestedSchema=undefined)
Ⓢ Ⓣ
(Function): pass the property & schema in, get a nestable typeValidator out
@Since
4.0.0-alpha.1
Arguments
property=undefined
(Primitive): property name of the currently nested schemanestedSchema=undefined
(Schema|Type): a nested schema with Type validators, or a Type validator
Returns
(Function): typeValidator
Example
// property name here is `dates`, then `created`, then `at`
nestedSchema = {
dates: {
created: {
at: 'date',
},
},
}
input = {
dates: {
created: {
at: new Date(),
},
},
}
input = new Date()
input = {
dates: {
mismatch: true,
},
}
scopedEncase
scopedEncase(fnToEncase=undefined, [type=undefined], [specification=undefined])
Ⓢ Ⓣ
Function
@Since
4.0.0-beta.1
Arguments
fnToEncase=undefined
(Function): depending on the result of this, call[type=undefined]
(|Function|string): Type[specification=undefined]
(|Function): Specification
Returns
(Function): the method...
Example
const fnToEncase = arg => arg === true
const onInvalid = (error, key, arg, instance) => console.log(arguments)
const onValid = (key, arg, instance) => console.log(arguments)
const encased = scopedEncase(fnToEncase).onValid(onValid).onInvalid(onInvalid)
//=> typedOnCall
set
set$$2
setChosen
setChosen(keyToSet=undefined, valueToSet=undefined)
Ⓢ Ⓣ
(Function): when fn is a full method, not an extended shorthand
@Since
0.5.0
Arguments
keyToSet=undefined
(Primitive): key we chose to setvalueToSet=undefined
(*): value we chose to set *(merged, existing, new)*
Returns
(*): .set or [keyToSet] return
Example
MergeChain.init(new Chain().extend(['eh']))
//isFunction: true => call parent[keyToSet](valueToSet)
setChosen('eh', 1)
//=> parent
parent.get('eh')
//=> 1
//=>isFunction: false => parent.set(keyToSet, valueToSet)
setChosen('oh', 1)
//=> parent //<- unless .set is overriden
parent.get('oh')
//=> 1
simpleKindOf
simpleKindOf(x=undefined)
Ⓢ Ⓣ
(Function): when Array -> 'array' when null -> 'null' else typeof x
@todos
- [ ]
type.split(' ').pop().replace(/\s\[\]/g, '').toLowerCase()
@Since
4.0.0
Arguments
x=undefined
(any): value for type
Returns
(string): type
split at space, replace brackets and space, lowercase
Example
simpleKindOf([]) //=> 'array'
simpleKindOf(null) //=> 'null'
simpleKindOf({}) //=> 'object'
this.extend
toArr
toArr(ar=undefined)
Ⓢ Ⓣ
(Function): anything into an array
@sig
- => Array
@Since
0.0.1
Arguments
ar=undefined
(any): turn this into an array
Returns
(Array): anything into an array
Example
toarr([])
// => []
toarr('')
// => ['']
toarr('1,2')
// => ['1', '2']
toarr('1,2')
// => ['1', '2']
const map = new Map()
map.set('eh', true)
const arr = toarr(map.entries())
// => ['eh', true]
const set = new Set()
set.add('eh')
set.add(true)
const arr = toarr(map.entries())
// => ['eh', true]
toarr('').concat(toarr(false)).concat(toarr(null))
// => ['', false, null]
toTest
toTest(matchable=undefined, [arg1=undefined], [arg2=undefined])
Ⓢ Ⓣ
(Function): like matcher, but .isMatch
@notes
- as else-if for easier ternary uglification
@Since
3.0.0
Arguments
matchable=undefined
(Matchable): any matchable[arg1=undefined]
(any): arg to match with[arg2=undefined]
(any): optional second arg to pass into tester
Returns
(boolean): is a match, passes the test
Example
matcher('kinga', 'kinga')
//=> true
matcher('k*nga', 'kinga')
//=> true
matcher('kinga', 'nope')
//=> false
matcher(new RegExp(/kinga/), 'kinga')
//=> true
matcher(new RegExp(/kinga/), 'nope')
//=> false
matcher(x => x === 'kinga', 'kinga')
//=> true
matcher(x => x === 'kinga', 'nope')
//=> false
matcher({ test: x => x === 'kinga' }, 'kinga')
//=> true
matcher({ test: x => x === 'kinga' }, 'nope')
//=> false
traverse
traversed
traversed()
Ⓢ Ⓣ
(Function): value traversed in traverse
@see
@Since
1.0.0
Returns
(*): traversed
Example
const traverser = new Traverser()
traverser.obj(['duck', 'duck', 'goose'])
traverser.vals(['g**se'])
traverser.traverse()
traverser.traversed()
//=> ['goose']
Example
const eh = {
me: true,
nested: {
really: {
deep: {
super: false,
not: 'eh',
canada: true,
modules: [{parser: 'hi'}],
},
matchme: 'minime',
notme: 'eh',
},
},
}
const chain = new Chain()
Object.assign(chain, eh)
const traverser = chain
.merge(eh)
.traverse(true)
.keys([/super/, /parser/, /store/, /meta/])
.vals([/minime/])
.call(false)
traverser.traversed()
//=> {
className: 'DotProp',
me: true,
nested: {
really: {
deep: {
not: 'eh',
canada: true,
modules: [{}],
},
notme: 'eh',
},
},
}