| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- 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
- switch (method) {
- case 'push':
- inserted = args
- break
- case 'unshift':
- inserted = args
- break
- case 'splice':
- inserted = args.slice(2)
- break
- }
- if (inserted) ob.observeArray(inserted)
- // 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
|