ValueSet.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. "use strict";
  2. /**
  3. * A set of values (i.e., `typedef unordered_set<Value, Value::Hash> ValueSet;`)
  4. * @class ValueSet
  5. * @namespace mungedb-aggregate.pipeline.expressions
  6. * @module mungedb-aggregate
  7. * @constructor
  8. */
  9. var ValueSet = module.exports = function ValueSet(vals) {
  10. this.set = {};
  11. if (vals instanceof Array)
  12. this.insertRange(vals);
  13. }, klass = ValueSet, proto = klass.prototype;
  14. proto._getKey = JSON.stringify;
  15. proto.hasKey = function hasKey(key) {
  16. return key in this.set;
  17. };
  18. //SKIPPED: proto.count -- use hasKey instead
  19. proto.has = function has(val) {
  20. return this._getKey(val) in this.set;
  21. };
  22. proto.insert = function insert(val) {
  23. var valKey = this._getKey(val);
  24. if (!this.hasKey(valKey)) {
  25. this.set[valKey] = val;
  26. return valKey;
  27. }
  28. return undefined;
  29. };
  30. proto.insertRange = function insertRange(vals) {
  31. var results = [];
  32. for (var i = 0, l = vals.length; i < l; i++)
  33. results.push(this.insert(vals[i]));
  34. return results;
  35. };
  36. proto.equals = function equals(other) {
  37. for (var key in this.set) {
  38. if (!other.hasKey(key))
  39. return false;
  40. }
  41. for (var otherKey in other.set) {
  42. if (!this.hasKey(otherKey))
  43. return false;
  44. }
  45. return true;
  46. };
  47. proto.values = function values() {
  48. var vals = [];
  49. for (var key in this.set)
  50. vals.push(this.set[key]);
  51. return vals;
  52. };
  53. proto.size = function values() {
  54. var n = 0;
  55. for (var key in this.set) //jshint ignore:line
  56. n++;
  57. return n;
  58. };
  59. proto.swap = function swap(other) {
  60. var tmp = this.set;
  61. this.set = other.set;
  62. other.set = tmp;
  63. };
  64. proto.eraseKey = function eraseKey(key) {
  65. delete this.set[key];
  66. };
  67. proto.erase = function erase(val) {
  68. var key = this._getKey(val);
  69. this.eraseKey(key);
  70. };
  71. proto.empty = function empty() {
  72. for (var key in this.set) //jshint ignore:line
  73. return false;
  74. return true;
  75. };