gitlab.com/thomasboni/go-enry/v2@v2.8.3-0.20220418031202-30b0d7a3de98/_testdata/JavaScript/namespace.js (about) 1 (function(root, factory) { 2 if (typeof define === 'function' && define.amd) { 3 define(['lodash'], factory); 4 } else if (typeof exports !== 'undefined') { 5 module.exports = factory(require('lodash')); 6 } else { 7 root.Namespace = factory(root._); 8 } 9 })(this, function(_) { 10 'use strict'; 11 12 /** 13 * @module namespace 14 * @class namespace 15 */ 16 function Namespace() {} 17 18 /** 19 * Regex for splitting keypaths into arrays. 20 * 21 * @private 22 * @const {RegExp} 23 * @type 24 */ 25 var KEYPATH_SPLITTER = /\./g; 26 27 /** 28 * An internal cache to avoid calculating a keypath more than once. 29 * 30 * @private 31 * @type {Object} 32 */ 33 var _keypaths = {}; 34 35 _.extend(Namespace.prototype, { 36 37 /** 38 * Adds a definition to the namespace object. 39 * 40 * @public 41 * @instance 42 * @method add 43 * @param {String} keypath - The keypath for the definition to be added at. 44 * @param {Function|Object} definition - The definition to be added. 45 * @return {Function|Object} - The definition. 46 */ 47 add: function(keypath, definition) { 48 return this._walk(keypath, function(memo, name, index, keypath) { 49 if (index + 1 === keypath.length) { 50 memo[name] = _.extend(definition, memo[name]); 51 } 52 return memo[name] || (memo[name] = {}); 53 }); 54 }, 55 56 /** 57 * Retrieves a definition from the namespace safely. 58 * 59 * @public 60 * @instance 61 * @method get 62 * @param {String} keypath - The keypath to lookup a definition for. 63 * @returns {Function|Object|undefined} - The definition if it exists, otherwise `undefined`. 64 */ 65 get: function(keypath) { 66 return this._walk(keypath); 67 }, 68 69 /** 70 * An internal function for walking a keypath. 71 * 72 * @private 73 * @instance 74 * @method _walk 75 * @param {String} keypath - The keypath to walk through. 76 * @param {Function} [callback] - An optional callback to be called at each item in the path. 77 * @returns {function|Object|undefined} - The reduced keypath. 78 */ 79 _walk: function(keypath, callback) { 80 return _.reduce( 81 _keypaths[keypath] || (_keypaths[keypath] = keypath.split(KEYPATH_SPLITTER)), 82 callback || function(memo, name) { 83 return memo && memo[name]; 84 }, 85 this 86 ); 87 } 88 }); 89 90 return Namespace; 91 }); 92 93 //# sourceMappingURL=namespace.js.map