lang.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. /**
  2. * Convert an Array-like object to a real Array.
  3. *
  4. * @param {Array-like} list
  5. * @param {Number} [i] - start index
  6. */
  7. var slice = [].slice
  8. exports.toArray = function (list, i) {
  9. return slice.call(list, i || 0)
  10. }
  11. /**
  12. * Mix properties into target object.
  13. *
  14. * @param {Object} to
  15. * @param {Object} from
  16. */
  17. exports.mixin = function (to, from) {
  18. for (var key in from) {
  19. if (to[key] !== from[key]) {
  20. to[key] = from[key]
  21. }
  22. }
  23. }
  24. /**
  25. * Mixin including non-enumerables, and copy property descriptors.
  26. *
  27. * @param {Object} to
  28. * @param {Object} from
  29. */
  30. exports.deepMixin = function (to, from) {
  31. Object.getOwnPropertyNames(from).forEach(function (key) {
  32. var descriptor = Object.getOwnPropertyDescriptor(from, key)
  33. Object.defineProperty(to, key, descriptor)
  34. })
  35. }
  36. /**
  37. * Proxy a property on one object to another.
  38. *
  39. * @param {Object} to
  40. * @param {Object} from
  41. * @param {String} key
  42. */
  43. exports.proxy = function (to, from, key) {
  44. if (to.hasOwnProperty(key)) return
  45. Object.defineProperty(to, key, {
  46. enumerable: true,
  47. configurable: true,
  48. get: function () {
  49. return from[key]
  50. },
  51. set: function (val) {
  52. from[key] = val
  53. }
  54. })
  55. }
  56. /**
  57. * Object type check. Only returns true
  58. * for plain JavaScript objects.
  59. *
  60. * @param {*} obj
  61. * @return {Boolean}
  62. */
  63. exports.isObject = function (obj) {
  64. return Object.prototype.toString.call(obj) === '[object Object]'
  65. }
  66. /**
  67. * Array type check.
  68. *
  69. * @param {*} obj
  70. * @return {Boolean}
  71. */
  72. exports.isArray = function (obj) {
  73. return Array.isArray(obj)
  74. }
  75. /**
  76. * Define a non-enumerable property
  77. *
  78. * @param {Object} obj
  79. * @param {String} key
  80. * @param {*} val
  81. * @param {Boolean} [enumerable]
  82. */
  83. exports.define = function (obj, key, val, enumerable) {
  84. Object.defineProperty(obj, key, {
  85. value : val,
  86. enumerable : !!enumerable,
  87. writable : true,
  88. configurable : true
  89. })
  90. }
  91. /**
  92. * Augment an target Object or Array by either
  93. * intercepting the prototype chain using __proto__,
  94. * or copy over property descriptors
  95. *
  96. * @param {Object|Array} target
  97. * @param {Object} proto
  98. */
  99. if ('__proto__' in {}) {
  100. exports.augment = function (target, proto) {
  101. target.__proto__ = proto
  102. }
  103. } else {
  104. exports.augment = exports.deepMixin
  105. }