Skip to content

Latest commit

 

History

History
762 lines (521 loc) · 31.3 KB

Collection.md

File metadata and controls

762 lines (521 loc) · 31.3 KB

Hord

A data storage and manipulation library for javascript

npm build coverage deps size vulnerabilities license


Collection ⇐ Array

An array of objects with optional model enforcement and indexed queries.

Extends: Array


new Collection([values])

import { Collection } from 'hord';

For info on indexing, see Collection.model. The collection class uses the on-change library (uses the Proxy API) to detect changes and maintain model enforcement and indexing.

Param Type Description
[values] object, Array.<object> Accepts an array of objects or multiple args of objects.


collection.length : number

✎ Updates indexes

Set or return the number of elements in the collection.

See: Array.length


collection.push(item) ⇒ number

✎ Updates indexes

Add an item to the end of the collection.

Returns: number - The new length of the collection.
See: Array.prototype.push()

Param Type Description
item unknown The item to add.


collection.pop() ⇒ unknown

✎ Updates indexes

Remove the last item from the collection and return it.

See: Array.prototype.pop()


collection.unshift(item) ⇒ number

✎ Updates indexes

Add an item to the beginning of the collection.

Returns: number - The new length of the collection.
See: Array.prototype.unshift()

Param Type Description
item unknown The item to add.


collection.shift() ⇒ unknown

✎ Updates indexes

Remove the first item from the collection and return it.

See: Array.prototype.shift()


collection.indexOf(item) ⇒ number

⚡ Utilizes indexes

Gets the index of the item using exact equality.

Returns: number - The index of the item or -1.

Param Type Description
item object The item to find.


collection.lastIndexOf(item) ⇒ number

⚡ Utilizes indexes

Gets the index of the last matching item.

Returns: number - The index of the item or -1.

Param Type Description
item object The item to find.


collection.includes(item) ⇒ boolean

⚡ Utilizes indexes

Determines if an item exists in the collection.

Param Type Description
item object The item to find.


collection.findIndex(predicate) ⇒ number

⚡ Utilizes indexes

Gets the index of the first (lowest index) matching item.

Returns: number - The index of the item or -1.

Param Type Description
predicate predicate A predicate to match against.


collection.findLastIndex(predicate) ⇒ number

⚡ Utilizes indexes

Gets the index of the last (greatest index) matching item.

Returns: number - The index of the item or -1.

Param Type Description
predicate predicate A predicate to match against.


collection.find(predicate) ⇒ object

⚡ Utilizes indexes

Gets the first (lowest index) matching item from the collection.

Returns: object - The item or undefined.

Param Type Description
predicate predicate A predicate to match against.


collection.findLast(predicate) ⇒ object

⚡ Utilizes indexes

Gets the last (greatest index) matching item from the collection.

Returns: object - The item or undefined.

Param Type Description
predicate predicate A predicate to match against.


collection.filter(predicate) ⇒ Collection

⚡ Utilizes indexes

Gets all the matching items from the collection.

Returns: Collection - A new Collection with the same model as the calling collection.

Param Type Description
predicate predicate A predicate to match against.


collection.sliceBy(beginPredicate, [endPredicate]) ⇒ Collection

⚡ Utilizes indexes

Like .slice(), but finds the begin and end indexes via predicates (end is included).

Returns: Collection - A new Collection with the same model as the calling collection.

Param Type Default Description
beginPredicate predicate A predicate to match against to get a beginning index.
[endPredicate] predicate collection.length A predicate to match against to get an ending index.


collection.first() ⇒ object

Gets the first item in the collection without removing it.


collection.last() ⇒ object

Gets the last item in the collection without removing it.


collection.slice([begin], [end]) ⇒ Collection

Returns a shallow copy of a portion of the collection selected from begin to end (end not included).

Returns: Collection - A new Collection with the same model as the calling collection.

Param Type Default Description
[begin] object 0 Index at which to begin extraction.
[end] object collection.length Index before which to end extraction.


collection.flatten([settings]) ⇒ Collection

Returns a new flattened collection.

Returns: Collection - A new Collection with the same model as the calling collection.

Param Type Default Description
[settings] object A settings object.
[settings.childKey] string "'children'" The key in which children are to be found.
[settings.saveDepth] boolean false If true appends a property "depth" to each returned object with the nested depth of the original object.
[settings.onParent] function Called on every parent item. Provides two args: the parent item and that item's parent. Context is set to the Collection. If true is returned, then the children will not be flattened.
[settings.onChild] function Called on every child item. Provides two args: the child item and that item's parent. Context is set to the Collection. If true is returned, then this item (and any children) will not be included in the output.


collection.nest([settings]) ⇒ Collection

⚡ Utilizes indexes

Returns a new nested collection.

Returns: Collection - A new Collection without a model.

Param Type Default Description
[settings] object A settings object.
[settings.idKey] string "'id'" The id property of items.
[settings.parentKey] string "'parent'" The key that holds the id of the parent item. Performance improvement if indexed.
[settings.childKey] string "'children'" The key to save children under. Performance improvement if indexed.
[settings.deleteParentKey] string false Should the parent key be deleted after nesting.


collection.unique([countKey]) ⇒ Collection

⚡ Utilizes indexes

Returns a new collection of deeply unique items.

Returns: Collection - A new Collection with the same model as the calling collection.

Param Type Description
[countKey] string If provided records the number of duplicates, starting at 1 for unique items.


collection.merge(collections, idKey, callback) ⇒ Collection

⚡ Utilizes indexes

Merges this collection with one or more other collections. Returns a new collection.

Returns: Collection - A new Collection with the same model as the calling collection.

Param Type Description
collections Collection, Array.<Collection> Either a collection or array of collections to merge with this collection.
idKey string The key to match items from the different collections.
callback function Called for each unique idKey value. Provides the same number of args as the total number of collections being merged, in the order provided. The returned value is included in the ouptput collection.


collection.concat(...collections) ⇒ Collection

Returns a shallow clone of this collection with the contents of one or more arrays or collections appended.

See: Array.prototype.concat()

Param Type Description
...collections Array, Collection One or more collections or arrays.


collection.toString() ⇒ string

See: Array.prototype.toString()


collection.toLocaleString([locales], [options]) ⇒ string

See: Array.prototype.toLocaleString()

Param Type
[locales] Array
[options] object


collection.join([separator]) ⇒ string

See: Array.prototype.join()

Param Type Default
[separator] string "','"


collection.entries() ⇒ Array.Iterator

See: Array.prototype.entries()


collection.values() ⇒ Array.Iterator

See: Array.prototype.values()


collection.keys() ⇒ object

See: Array.prototype.keys()


collection.forEach(callback, [thisArg]) ⇒ object     🔗 Chainable

Calls a provided callback once for each array element in order starting at 0. Unlike the native forEach, this one returns an instance of collection for chaining.

Returns: object - Returns this.
See: Array.prototype.forEach()

Param Type Default Description
callback function Provides two arguments, the element and the index of the element.
[thisArg] unknown this A value to use as this when executing callback.


collection.forEachRight(callback, [thisArg]) ⇒ object     🔗 Chainable

Like .forEach(), but starts on the last (greatest index) item and progresses backwards.

Returns: object - Returns this.

Param Type Default Description
callback function Provides two arguments, the element and the index of the element.
[thisArg] unknown this A value to use as this when executing callback.


collection.some(callback, [thisArg]) ⇒ boolean

See: Array.prototype.some()

Param Type Default Description
callback function Provides two arguments, the element and the index of the element.
[thisArg] object this A value to use as this when executing callback.


collection.someRight(callback, [thisArg]) ⇒ boolean

Like .some(), but starts on the last (greatest index) item and progresses backwards.

Param Type Default Description
callback function Provides two arguments, the element and the index of the element.
[thisArg] object this A value to use as this when executing callback.


collection.every(callback, [thisArg]) ⇒ boolean

See: Array.prototype.every()

Param Type Default Description
callback function Provides two arguments, the element and the index of the element.
[thisArg] object this A value to use as this when executing callback.


collection.reduce(callback, [thisArg]) ⇒ unknown

See: Array.prototype.reduce()

Param Type Default Description
callback function
[thisArg] object this A value to use as this when executing callback.


collection.reduceRight(callback, [thisArg]) ⇒ unknown

See: Array.prototype.reduceRight()

Param Type Default Description
callback function
[thisArg] object this A value to use as this when executing callback.


collection.map(callback, thisArg) ⇒ Collection

Returns a new collection with the results of calling a provided function on every element.

Returns: Collection - A new Collection without a model.

Param Type Description
callback function Function that produces an element of the new Array, taking three arguments: the current item, index, and the collection. Context is also set to this collection.
thisArg unknown Applied to the context of the callback.


collection.eachChild(onChild, [settings])

Calls a callback for each nested child.

Param Type Default Description
onChild function Called for each item and child item. If true is returned, all iteration stops. Provides three args: the child item, the nested depth of the item, and the items parent. Context is set to this Collection.
[settings] object Optional settings object.
[settings.childKey] string "children" The key that contains children items.
[settings.onParent] function Called for each item that contains children. If true is returned, then the children will not get processed. Provides the same args and context as the onChild callback.


collection.flat([depth]) ⇒ Collection

Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Returns: Collection - A new Collection without a model.
See: Array.prototype.flat()

Param Type Default
[depth] number 1


collection.flatMap(callback, thisArg) ⇒ Collection

Maps each element using a mapping function, then flattens the result into a new array. Same as .map().flat().

Returns: Collection - A new Collection without a model.
See: Array.prototype.flatMap()

Param Type
callback function
thisArg unknown


collection.model(model) ⇒ Model     🔗 Chainable

✎ Builds indexes

A model that gets enforced on every item in the collection. To create indexes, add 'index: true' to the schema type definition like in the example below.

Param Type Description
model Model, object Can be an instance of class:Model or an object with a schema structure.

Example

import { Collection, Model } from 'hord';

const Person = new Model({
    id: {
        type: Number,
        index: true
    },
    first: {
        type: String,
        index: true
    },
    last: {
        type: String,
        index: true
    },
    age: Number
});

const people = new Collection().model(Person);

// OR

const people = new Collection().model({
    id: {
        type: Number,
        index: true
    },
    first: {
        type: String,
        index: true
    },
    last: {
        type: String,
        index: true
    },
    age: Number
});


collection.remove()

Removes all model onChange events and indexes and empties the collection.


collection.copyWithin(target, [start], [end]) ⇒ object     🔗 Chainable

⚠ Forces a rebuild of all indexes

Shallow copies a portion of the collection to another location within the collection.

Returns: object - Returns `this'.
See: Array.prototype.copyWithin()

Param Type Default Description
target number Index at which to copy the sequence to. If negative, target will be counted from the end. If target is at or greater than arr.length, nothing will be copied. If target is positioned after start, the copied sequence will be trimmed to fit arr.length.
[start] number 0 Index at which to start copying elements from. If negative, start will be counted from the end. If start is omitted, copyWithin will copy from index 0.
[end] number this.length Index at which to end copying elements from. copyWithin copies up to but not including end. If negative, end will be counted from the end. If end is omitted, copyWithin will copy until the last index (default to arr.length).


collection.fill(value, [start], [end]) ⇒ object     🔗 Chainable

⚠ Forces a rebuild of all indexes

Fills all or a portion of the collection with a static value.

Returns: object - Returns `this'.
See: Array.prototype.fill()

Param Type Default Description
value unknown Value to fill the array with.
[start] number 0 Start index.
[end] number this.length End index.


collection.reverse() ⇒ object     🔗 Chainable

⚠ Forces a rebuild of all indexes

Reverses the order of items in place.

Returns: object - Returns this.
See: Array.prototype.reverse()


collection.sort([compareFunction]) ⇒ object     🔗 Chainable

⚠ Forces a rebuild of all indexes

Sort the contents of the collection in place.

Returns: object - Returns this.

Param Type Default Description
[compareFunction] function List.comparers.default A sorter function. See Array.prototype.sort().


collection.splice(start, [deleteCount], [...newValues]) ⇒ Collection

✎ Updates indexes

Changes the contents of an collection in place by removing or replacing existing elements and/or adding new elements.

Returns: Collection - A new Collection with the same model as the calling collection. Contains the elements removed from the calling collection.
See: Array.prototype.splice()

Param Type Default Description
start number Index to start the splice.
[deleteCount] number 0 Number of elements to delete.
[...newValues] * Any values to add.


predicate : function | object

Can be either of the following:

  • A function that accepts one item from the collection and returns true to indicate a match.
  • A query object that is deeply compared to items in the collection. Available operators are outlined below.

Query Operators

$eq (Equal)

The same as not providing any operator. Uses SameValue equality.

{age: 23}
// OR
{age: {$eq: 23}}

$ne (Not Equal)

Like $eq, $ne uses SameValue equality, but matches values that don't equal.

{age: {$ne: 23}}

$in (IN)

Matches any item in an array.

{age: {$in: [20, 30, 40]}}

$nin (Not IN)

Matches any item not in an array.

{age: {$nin: [20, 30, 40]}}

$gt (Greater Than)

Matches values greater than the provided value

{age: {$gt: 21}}

$gte (Greater Than or Equal)

Matches values greater than the provided value

{age: {$gte: 21}}

$lt (Less Than)

Matches values greater than the provided value

{age: {$lt: 21}}

$lte (Less Than or Equal)

Matches values greater than the provided value

{age: {$lte: 21}}

If you haven't set up any indexes, or you're searching on properties that aren't indexed, then providing a function will most likely have better performance. If you're searching on even one property that's indexed, then using an object will perform better, as the indexer can narrow the search before iterating over the results for a final match.