index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*!
  2. * set-getter (https://github.com/doowb/set-getter)
  3. *
  4. * Copyright (c) 2016, Brian Woodward.
  5. * Licensed under the MIT License.
  6. */
  7. 'use strict';
  8. var toPath = require('to-object-path');
  9. /**
  10. * Defines a getter function on an object using property path notation.
  11. *
  12. * ```js
  13. * var obj = {};
  14. * getter(obj, 'foo', function() {
  15. * return 'bar';
  16. * });
  17. * ```
  18. * @param {Object} `obj` Object to add property to.
  19. * @param {String|Array} `prop` Property string or array to add.
  20. * @param {Function} `getter` Getter function to add as a property.
  21. * @api public
  22. */
  23. function setGetter(obj, prop, getter) {
  24. var key = toPath(arguments);
  25. return define(obj, key, getter);
  26. }
  27. /**
  28. * Define getter function on object or object hierarchy using dot notation.
  29. *
  30. * @param {Object} `obj` Object to define getter property on.
  31. * @param {String} `prop` Property string to define.
  32. * @param {Function} `getter` Getter function to define.
  33. * @return {Object} Returns original object.
  34. */
  35. function define(obj, prop, getter) {
  36. if (!~prop.indexOf('.')) {
  37. defineProperty(obj, prop, getter);
  38. return obj;
  39. }
  40. var keys = prop.split('.');
  41. var last = keys.pop();
  42. var target = obj;
  43. var key;
  44. while ((key = keys.shift())) {
  45. while (key.slice(-1) === '\\') {
  46. key = key.slice(0, -1) + '.' + keys.shift();
  47. }
  48. target = target[key] || (target[key] = {});
  49. }
  50. defineProperty(target, last, getter);
  51. return obj;
  52. }
  53. /**
  54. * Define getter function on object as a configurable and enumerable property.
  55. *
  56. * @param {Object} `obj` Object to define property on.
  57. * @param {String} `prop` Property to define.
  58. * @param {Function} `getter` Getter function to define.
  59. */
  60. function defineProperty(obj, prop, getter) {
  61. Object.defineProperty(obj, prop, {
  62. configurable: true,
  63. enumerable: true,
  64. get: getter
  65. });
  66. }
  67. /**
  68. * Expose `setGetter`
  69. */
  70. module.exports = setGetter;