Skip to content

Instantly share code, notes, and snippets.

@codebryo
Created July 3, 2017 15:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codebryo/6dfab342989999d263cecc0684e7244a to your computer and use it in GitHub Desktop.
Save codebryo/6dfab342989999d263cecc0684e7244a to your computer and use it in GitHub Desktop.
Javascript collection Model
class Model {
constructor(arr = []) {
if (!_.isArray(arr))
throw new Error('First model param needs to be an Array!')
this._collection = new Array(...arr)
}
/**
* Get size
* -- return the amount of elements in the collection
* @return {Integer}
*/
get size() {
return this._collection.length
}
/**
* Get all
* -- returns the whole collection
* @return {Array}
*/
get all() {
return this._collection.slice()
}
/**
* Get first
* -- returns the first element of an collection
* @return {Any}
*/
get first() {
let item = this._collection.slice(0, 1)
return item ? item[0] : item
}
/**
* Get last
* -- returns the last element of an collection
* @return {Any}
*/
get last() {
let item = this._collection.slice(-1)
return item ? item[0] : item
}
/**
* Record
* -- Add elements to the collection
* @param {Array} arr
* @return {Void}
*/
record(arr) {
if (!_.isArray(arr)) return
arr.forEach(item => this._collection.push(item))
return this.all
}
/**
* Update
* -- Update objects in the collection. Identified by a given prop.
* @param {Array} arr
* @param {String|Optional} prop (default 'id')
* @return {Void}
*/
update(arr, prop = 'id') {
if (!_.isArray(arr)) return
arr.forEach(item => {
let currentIndex = 0
let updateRecord = this._collection.some((row, index) => {
currentIndex = index
return row[prop] === item[prop]
})
if (updateRecord) {
return _.merge(this._collection[currentIndex], item)
}
return this.record([item])
})
}
/**
* Find
* -- Find an object in the collection by a certain property.
* @param {Any} val
* @param {String|Optional} prop (default 'id')
* @return {Object|Void}
*/
find(val, prop = 'id') {
let currentIndex = 0
let recordFound = this._collection.some((record, index) => {
currentIndex = index
if (Array.isArray(val)) return val.indexOf(record[prop]) > -1
return record[prop] === val
})
if (recordFound) return this._collection[currentIndex]
return
}
/**
* Destroy
* -- Find an object in the collection and remove it
* @param {Object} row
* @return {Object|Void}
*/
destroy(row) {
row = JSON.stringify(row)
const indexToRemove = _.findIndex(this._collection, record => {
return JSON.stringify(record) === row
})
if (indexToRemove >= 0) return _.pullAt(this._collection, [indexToRemove])
return
}
/**
* Empty
* -- Empty the local collection
* @return {Object|Void}
*/
empty() {
this._collection = []
}
}
module.exports = Model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment