AddToSetAccumulator.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. var sha3 = require('sha3'),
  2. AddToSetAccumulator = module.exports = (function(){
  3. // Constructor
  4. var klass = module.exports = function AddToSetAccumulator(){
  5. this.set = {};
  6. base.call(this);
  7. }, Accumulator = require("./Accumulator"), base = Accumulator, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  8. proto.evaluate = function evaluate(doc){
  9. if(this.operands.length != 1) throw new Error("this should never happen");
  10. var v = this.operands[0].evaluate(doc);
  11. if(v)
  12. this.set[this._getHashForObject(v)] = v;
  13. return null;
  14. };
  15. proto._getHashForObject = function _getHashForObject(obj){
  16. // TODO: This uses JSON.stringify which is going to be really slow for any signficant amount of data
  17. // Need to figure out a better way to do hasing in Javascript for objects
  18. var d = new sha3.SHA3Hash();
  19. d.update(JSON.stringify(obj));
  20. return d.digest('hex');
  21. };
  22. proto.getValue = function getValue(){
  23. var values = [], n = 0;
  24. for(var key in this.set){
  25. if(this.set.hasOwnProperty(key)) values[n++] = this.set[key];
  26. }
  27. return values;
  28. };
  29. proto.getOpName = function getOpName(){
  30. return "$addToSet";
  31. };
  32. return klass;
  33. })();