SubstrExpression.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. /**
  3. * A $substr pipeline expression.
  4. * @see evaluateInternal
  5. * @class SubstrExpression
  6. * @namespace mungedb-aggregate.pipeline.expressions
  7. * @module mungedb-aggregate
  8. * @constructor
  9. **/
  10. var SubstrExpression = module.exports = function SubstrExpression() {
  11. this.nargs = 3;
  12. base.call(this);
  13. }, klass = SubstrExpression,
  14. base = require("./NaryExpression"),
  15. proto = klass.prototype = Object.create(base.prototype, {
  16. constructor: {
  17. value: klass
  18. }
  19. });
  20. // DEPENDENCIES
  21. var Value = require("../Value"),
  22. Expression = require("./Expression");
  23. // PROTOTYPE MEMBERS
  24. proto.getOpName = function getOpName() {
  25. return "$substr";
  26. };
  27. /**
  28. * 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.
  29. * @method evaluateInternal
  30. **/
  31. proto.evaluateInternal = function evaluateInternal(vars) {
  32. var val = this.operands[0].evaluateInternal(vars),
  33. idx = this.operands[1].evaluateInternal(vars),
  34. len = this.operands[2].evaluateInternal(vars),
  35. str = Value.coerceToString(val);
  36. if (typeof(idx) != "number") throw new Error(this.getOpName() + ": starting index must be a numeric type; code 16034");
  37. if (typeof(len) != "number") throw new Error(this.getOpName() + ": length must be a numeric type; code 16035");
  38. if (idx >= str.length) return "";
  39. //TODO: Need to handle -1
  40. len = (len === -1 ? undefined : len);
  41. return str.substr(idx, len);
  42. };
  43. /** Register Expression */
  44. Expression.registerExpression("$substr", base.parse(SubstrExpression));