namespace.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * class Namespace
  3. *
  4. * Simple object for storing attributes. Implements equality by attribute names
  5. * and values, and provides a simple string representation.
  6. *
  7. * See also [original guide][1]
  8. *
  9. * [1]:http://docs.python.org/dev/library/argparse.html#the-namespace-object
  10. **/
  11. 'use strict';
  12. var $$ = require('./utils');
  13. /**
  14. * new Namespace(options)
  15. * - options(object): predefined propertis for result object
  16. *
  17. **/
  18. var Namespace = module.exports = function Namespace(options) {
  19. $$.extend(this, options);
  20. };
  21. /**
  22. * Namespace#isset(key) -> Boolean
  23. * - key (string|number): property name
  24. *
  25. * Tells whenever `namespace` contains given `key` or not.
  26. **/
  27. Namespace.prototype.isset = function (key) {
  28. return $$.has(this, key);
  29. };
  30. /**
  31. * Namespace#set(key, value) -> self
  32. * -key (string|number|object): propery name
  33. * -value (mixed): new property value
  34. *
  35. * Set the property named key with value.
  36. * If key object then set all key properties to namespace object
  37. **/
  38. Namespace.prototype.set = function (key, value) {
  39. if (typeof (key) === 'object') {
  40. $$.extend(this, key);
  41. } else {
  42. this[key] = value;
  43. }
  44. return this;
  45. };
  46. /**
  47. * Namespace#get(key, defaultValue) -> mixed
  48. * - key (string|number): property name
  49. * - defaultValue (mixed): default value
  50. *
  51. * Return the property key or defaulValue if not set
  52. **/
  53. Namespace.prototype.get = function (key, defaultValue) {
  54. return !this[key] ? defaultValue : this[key];
  55. };
  56. /**
  57. * Namespace#unset(key, defaultValue) -> mixed
  58. * - key (string|number): property name
  59. * - defaultValue (mixed): default value
  60. *
  61. * Return data[key](and delete it) or defaultValue
  62. **/
  63. Namespace.prototype.unset = function (key, defaultValue) {
  64. var value = this[key];
  65. if (value !== null) {
  66. delete this[key];
  67. return value;
  68. }
  69. return defaultValue;
  70. };