remove.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var helperDeleteProperty = require('./helperDeleteProperty')
  2. var isFunction = require('./isFunction')
  3. var isArray = require('./isArray')
  4. var each = require('./each')
  5. var arrayEach = require('./arrayEach')
  6. var lastEach = require('./lastEach')
  7. var clear = require('./clear')
  8. var eqNull = require('./eqNull')
  9. function pluckProperty (name) {
  10. return function (obj, key) {
  11. return key === name
  12. }
  13. }
  14. /**
  15. * 移除对象属性
  16. *
  17. * @param {Object/Array} obj 对象/数组
  18. * @param {Function/String} iterate 方法或属性
  19. * @param {Object} context 上下文
  20. * @return {Object/Array}
  21. */
  22. function remove (obj, iterate, context) {
  23. if (obj) {
  24. if (!eqNull(iterate)) {
  25. var removeKeys = []
  26. var rest = []
  27. if (!isFunction(iterate)) {
  28. iterate = pluckProperty(iterate)
  29. }
  30. each(obj, function (item, index, rest) {
  31. if (iterate.call(context, item, index, rest)) {
  32. removeKeys.push(index)
  33. }
  34. })
  35. if (isArray(obj)) {
  36. lastEach(removeKeys, function (item, key) {
  37. rest.push(obj[item])
  38. obj.splice(item, 1)
  39. })
  40. } else {
  41. rest = {}
  42. arrayEach(removeKeys, function (key) {
  43. rest[key] = obj[key]
  44. helperDeleteProperty(obj, key)
  45. })
  46. }
  47. return rest
  48. }
  49. return clear(obj)
  50. }
  51. return obj
  52. }
  53. module.exports = remove