FieldPath.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var FieldPath = module.exports = FieldPath = (function(){
  2. // CONSTRUCTOR
  3. /**
  4. * Constructor for field paths.
  5. *
  6. * The constructed object will have getPathLength() > 0.
  7. * Uassert if any component field names do not pass validation.
  8. *
  9. * @param fieldPath the dotted field path string or non empty pre-split vector.
  10. **/
  11. var klass = function FieldPath(path){
  12. var fields = typeof(path) === "object" && typeof(path.length) === "number" ? path : path.split(".");
  13. if(fields.length === 0) throw new Error("FieldPath cannot be constructed from an empty Strings or Arrays.; code 16409");
  14. for(var i = 0, n = fields.length; i < n; ++i){
  15. var field = fields[i];
  16. if(field.length === 0) throw new Error("FieldPath field names may not be empty strings; code 15998");
  17. if(field[0] == "$") throw new Error("FieldPath field names may not start with '$'; code 16410");
  18. if(field.indexOf("\0") != -1) throw new Error("FieldPath field names may not contain '\\0'; code 16411");
  19. if(field.indexOf(".") != -1) throw new Error("FieldPath field names may not contain '.'; code 16412");
  20. }
  21. this.path = path;
  22. this.fields = fields;
  23. }, base = Object, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  24. // STATIC MEMBERS
  25. klass.PREFIX = "$";
  26. // PROTOTYPE MEMBERS
  27. /**
  28. * Get the full path.
  29. *
  30. * @param fieldPrefix whether or not to include the field prefix
  31. * @returns the complete field path
  32. */
  33. proto.getPath = function getPath(withPrefix) {
  34. return ( !! withPrefix ? FieldPath.PREFIX : "") + this.fields.join(".");
  35. };
  36. /** A FieldPath like this but missing the first element (useful for recursion). Precondition getPathLength() > 1. **/
  37. proto.tail = function tail() {
  38. return new FieldPath(this.fields.slice(1));
  39. };
  40. /**
  41. * Get a particular path element from the path.
  42. *
  43. * @param i the zero based index of the path element.
  44. * @returns the path element
  45. */
  46. proto.getFieldName = function getFieldName(i){ //TODO: eventually replace this with just using .fields[i] directly
  47. return this.fields[i];
  48. };
  49. /**
  50. * Get the number of path elements in the field path.
  51. *
  52. * @returns the number of path elements
  53. **/
  54. proto.getPathLength = function getPathLength() {
  55. return this.fields.length;
  56. };
  57. return klass;
  58. })();