Нет описания

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*!
  2. * copy-descriptor <https://github.com/jonschlinkert/copy-descriptor>
  3. *
  4. * Copyright (c) 2015, Jon Schlinkert.
  5. * Licensed under the MIT License.
  6. */
  7. 'use strict';
  8. /**
  9. * Copy a descriptor from one object to another.
  10. *
  11. * ```js
  12. * function App() {
  13. * this.cache = {};
  14. * }
  15. * App.prototype.set = function(key, val) {
  16. * this.cache[key] = val;
  17. * return this;
  18. * };
  19. * Object.defineProperty(App.prototype, 'count', {
  20. * get: function() {
  21. * return Object.keys(this.cache).length;
  22. * }
  23. * });
  24. *
  25. * copy(App.prototype, 'count', 'len');
  26. *
  27. * // create an instance
  28. * var app = new App();
  29. *
  30. * app.set('a', true);
  31. * app.set('b', true);
  32. * app.set('c', true);
  33. *
  34. * console.log(app.count);
  35. * //=> 3
  36. * console.log(app.len);
  37. * //=> 3
  38. * ```
  39. * @name copy
  40. * @param {Object} `receiver` The target object
  41. * @param {Object} `provider` The provider object
  42. * @param {String} `from` The key to copy on provider.
  43. * @param {String} `to` Optionally specify a new key name to use.
  44. * @return {Object}
  45. * @api public
  46. */
  47. module.exports = function copyDescriptor(receiver, provider, from, to) {
  48. if (!isObject(provider) && typeof provider !== 'function') {
  49. to = from;
  50. from = provider;
  51. provider = receiver;
  52. }
  53. if (!isObject(receiver) && typeof receiver !== 'function') {
  54. throw new TypeError('expected the first argument to be an object');
  55. }
  56. if (!isObject(provider) && typeof provider !== 'function') {
  57. throw new TypeError('expected provider to be an object');
  58. }
  59. if (typeof to !== 'string') {
  60. to = from;
  61. }
  62. if (typeof from !== 'string') {
  63. throw new TypeError('expected key to be a string');
  64. }
  65. if (!(from in provider)) {
  66. throw new Error('property "' + from + '" does not exist');
  67. }
  68. var val = Object.getOwnPropertyDescriptor(provider, from);
  69. if (val) Object.defineProperty(receiver, to, val);
  70. };
  71. function isObject(val) {
  72. return {}.toString.call(val) === '[object Object]';
  73. }