Peter Arrenbrecht avatar Peter Arrenbrecht committed 6234113

refactor ancestors and descendants

* extract common code
* make descendants use the cached children

Comments (0)

Files changed (1)

         assert hds
         return hds
 
-    def descendants(self, start, stop=None):
-        children = {}
-        for n in self.walk():
-            ps = self.parents(n)
-            for p in ps:
-                children.setdefault(p, []).append(n)
-
+    def _relatives(self, relativesfn, start, stop=None):
         if stop is not None:
             seen = set(stop)
         else:
             seen = set()
-
-        d = set()
+        rels = set()
         pending = list(start)
         while pending:
             n = pending.pop()
             if n not in seen:
-                d.add(n)
+                rels.add(n)
                 seen.add(n)
-                pending.extend(children.get(n, []))
-        return d
+                pending.extend(relativesfn(n))
+        return rels
+
+    def descendants(self, start, stop=None):
+        return self._relatives(self.children, start, stop)
 
     def ancestors(self, start, stop=None):
-        if stop is not None:
-            seen = set(stop)
-        else:
-            seen = set()
-
-        d = set()
-        pending = list(start)
-        while pending:
-            n = pending.pop()
-            if n not in seen:
-                d.add(n)
-                seen.add(n)
-                pending.extend(self.parents(n))
-        return d
+        return self._relatives(self.parents, start, stop)
 
     def walk(self, heads=None, stops=None):
         '''iterate ids from heads to stops (or root), depth-first'''
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.