Source: models/Node.js

  1. require('../polyfill');
  2. /**
  3. * Mixin type that allows path items (Depot, Dir, and File) to operate like a
  4. * tree easily.
  5. *
  6. * A node requires that the implementing class provide certain basic properties:
  7. *
  8. * 1. `this.children`: If the node contains children, this should be defined as an
  9. * empty array.
  10. *
  11. * 2. `this.pathId`: This should be an array of path names indicating the
  12. * absolute location in an easily comparable way.
  13. *
  14. * 3. `this.name`: The comparable string 'name' of the item
  15. *
  16. * @mixin
  17. */
  18. var Node = {
  19. /**
  20. *
  21. */
  22. sortChildren: function() {
  23. this.children.sort(function(a, b) { return a.name.localeCompare(b.name); });
  24. },
  25. /**
  26. * Inserts the child into the tree, if it belongs.
  27. *
  28. * @param child
  29. * @return {boolean} Returns true if the child is inserted
  30. */
  31. insert: function (child) {
  32. if (!this.children) {
  33. return false;
  34. }
  35. if (child.isChildRelation(this)) {
  36. this.children.push(child);
  37. return true;
  38. }
  39. for (var index = 0; index < this.children.length; index++) {
  40. if (this.children[index].insert(child)) {
  41. return true;
  42. }
  43. }
  44. return false;
  45. },
  46. /**
  47. * Validates that the current node could be a child of the indicated parent.
  48. *
  49. * @param parent The potential parent
  50. */
  51. isChildRelation: function (parent) {
  52. return (this.pathId.length == (parent.pathId.length + 1)) &&
  53. (this.getParentName() == parent.name);
  54. },
  55. /**
  56. * Returns the parent name of this node.
  57. *
  58. * @return {string}
  59. */
  60. getParentName: function () {
  61. if (this.pathId.length > 1) {
  62. return this.pathId[this.pathId.length - 2];
  63. }
  64. return undefined;
  65. }
  66. };
  67. module.exports = Node;