all files / src/ collection.js

100% Statements 20/20
100% Branches 2/2
100% Functions 5/5
100% Lines 20/20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55             11× 11×       55× 55×                           60× 60× 60× 60×                 60× 60× 60× 60×   60× 128×        
const forEach = Array.prototype.forEach
 
/**
 * 选择第几个元素
 * @param {number} index 序号. 负数表示从后往前
 */
export function eq (index) {
  const length = this._collections.length
  return new this.init(this._collections[index >= 0 ? index : length + index])
}
 
export function map (callback) {
  Array.prototype.map.call(this._collections, callback)
  return this
}
/**
 * 过滤回调
 * @param {function} callback
 */
export function filter (callback) {
  const newCollections = Array.prototype.filter.call(this._collections, callback)
  setCollection(this, newCollections)
  return this
}
 
/**
 * 清空 DOM 节点
 * @param {$} context 上下文
 */
export function clearCollection (context) {
  let num = 0
  context.length = 0
  context._collections = []
  while (context[num]) {
    delete context[num]
    num++
  }
}
/**
 * 在当前实例上 添加集合
 * @param {$} context 当前上下文
 * @param {collection} collection  集合
 */
export function setCollection (context, collection) {
  clearCollection(context)
  context._collections = collection
  context.length = collection.length
  let i = 0
  // for 的性能比 forEach 和 map 要快了一倍...
  for (; i < context.length; i++) {
    context[i] = collection[i]
  }
 
}