SubstrExpression.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. /**
  3. * A $substr pipeline expression.
  4. * @see evaluate
  5. * @class SubstrExpression
  6. * @namespace mungedb-aggregate.pipeline.expressions
  7. * @module mungedb-aggregate
  8. * @constructor
  9. **/
  10. var SubstrExpression = module.exports = function SubstrExpression(){
  11. if (arguments.length !== 0) throw new Error("zero args expected");
  12. base.call(this);
  13. }, klass = SubstrExpression, base = require("./NaryExpression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  14. // DEPENDENCIES
  15. var Value = require("../Value");
  16. // PROTOTYPE MEMBERS
  17. proto.getOpName = function getOpName(){
  18. return "$substr";
  19. };
  20. proto.addOperand = function addOperand(expr) {
  21. this.checkArgLimit(3);
  22. base.prototype.addOperand.call(this, expr);
  23. };
  24. /**
  25. * Takes a string and two numbers. The first number represents the number of bytes in the string to skip, and the second number specifies the number of bytes to return from the string.
  26. * @method evaluate
  27. **/
  28. proto.evaluate = function evaluate(doc) {
  29. this.checkArgCount(3);
  30. var val = this.operands[0].evaluate(doc),
  31. idx = this.operands[1].evaluate(doc),
  32. len = this.operands[2].evaluate(doc),
  33. str = Value.coerceToString(val);
  34. if (typeof(idx) != "number") throw new Error(this.getOpName() + ": starting index must be a numeric type; code 16034");
  35. if (typeof(len) != "number") throw new Error(this.getOpName() + ": length must be a numeric type; code 16035");
  36. if (idx >= str.length) return "";
  37. //TODO: Need to handle -1
  38. len = (len === -1 ? undefined : len);
  39. return str.substr(idx, len);
  40. };