Sha256: 0cd1490cbabcec22ea8c1748896af7d78fe50b7b702a08bb5adfc419bce42765
Contents?: true
Size: 1.88 KB
Versions: 3
Compression:
Stored size: 1.88 KB
Contents
var _ = require('../util') var arrayProto = Array.prototype var arrayMethods = Object.create(arrayProto) /** * Intercept mutating methods and emit events */ ;[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method var original = arrayProto[method] _.define(arrayMethods, method, function mutator () { // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length var args = new Array(i) while (i--) { args[i] = arguments[i] } var result = original.apply(this, args) var ob = this.__ob__ var inserted, removed switch (method) { case 'push': inserted = args break case 'unshift': inserted = args break case 'splice': inserted = args.slice(2) removed = result break case 'pop': case 'shift': removed = [result] break } if (inserted) ob.observeArray(inserted) if (removed) ob.unobserveArray(removed) // notify change ob.notify() return result }) }) /** * Swap the element at the given index with a new value * and emits corresponding event. * * @param {Number} index * @param {*} val * @return {*} - replaced element */ _.define( arrayProto, '$set', function $set (index, val) { if (index >= this.length) { this.length = index + 1 } return this.splice(index, 1, val)[0] } ) /** * Convenience method to remove the element at given index. * * @param {Number} index * @param {*} val */ _.define( arrayProto, '$remove', function $remove (index) { /* istanbul ignore if */ if (!this.length) return if (typeof index !== 'number') { index = _.indexOf(this, index) } if (index > -1) { return this.splice(index, 1) } } ) module.exports = arrayMethods
Version data entries
3 entries across 3 versions & 1 rubygems