FieldPath.js 2.2 KB

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