Geen omschrijving

namespace.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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('underscore');
  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. } else {
  69. return defaultValue;
  70. }
  71. };