Path.js.flow 635 B

123456789101112131415161718192021222324252627282930
  1. // @flow strict
  2. export type Path = {|
  3. +prev: Path | void,
  4. +key: string | number,
  5. +typename: string | void,
  6. |};
  7. /**
  8. * Given a Path and a key, return a new Path containing the new key.
  9. */
  10. export function addPath(
  11. prev: $ReadOnly<Path> | void,
  12. key: string | number,
  13. typename: string | void,
  14. ): Path {
  15. return { prev, key, typename };
  16. }
  17. /**
  18. * Given a Path, return an Array of the path keys.
  19. */
  20. export function pathToArray(path: ?$ReadOnly<Path>): Array<string | number> {
  21. const flattened = [];
  22. let curr = path;
  23. while (curr) {
  24. flattened.push(curr.key);
  25. curr = curr.prev;
  26. }
  27. return flattened.reverse();
  28. }