Skip to content

Commit

Permalink
tree reindexing & sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
dakujem committed Jan 19, 2024
1 parent 4247e80 commit 0e997f7
Show file tree
Hide file tree
Showing 6 changed files with 419 additions and 334 deletions.
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -608,4 +608,4 @@ composer test

Ideas or contribution is welcome. Please send a PR or submit an issue.

And if you happen to like the library, spread the word 🙏.
And if you happen to like the library, give it a star and spread the word 🙏.
11 changes: 10 additions & 1 deletion src/Seed.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,19 @@ public static function attr(string|int $name, mixed $default = null): callable

/**
* Accepts any iterable and returns an iterator.
* Useful where en iterator is required, but any iterable or array is provided.
* Useful where an iterator is required, but an iterable type is provided.
*/
public static function iterator(iterable $input): Iterator
{
return is_array($input) ? new ArrayIterator($input) : new IteratorIterator($input);
}

/**
* Accepts any iterable and returns an array.
* Useful where an array is required, but an iterable type is provided.
*/
public static function array(iterable $input): array
{
return is_array($input) ? $input : iterator_to_array($input);
}
}
31 changes: 30 additions & 1 deletion src/Tree.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
/**
* A helper class for high-level tree operations.
*
* This contrasts with the low-level interface.
* This contrasts with the low-level interface of movable nodes:
* @see MovableNodeContract
*
* @author Andrej Rypak <[email protected]>
Expand Down Expand Up @@ -115,6 +115,35 @@ public static function unlinkChildren(
$parent->removeChildren();
}

/**
*
* Usage of <=> (spaceship) operator to compare based on path props:
* fn(Node $a, Node $b) => $a->data()->path <=> $b->data()->path
*
*/
public static function reindexTree(
MovableNodeContract $node,
?callable $key,
?callable $sort,
): void {
$children = Seed::array($node->children());
$node->removeChildren();
if (null !== $sort) {
uasort($children, $sort);
}
$seq = 0;
foreach ($children as $childKey => $child) {
if (!$child instanceof MovableNodeContract) {
// TODO improve exceptions
throw new Exception('Child not movable.');
}
$newKey = null !== $key ? $key($child, $childKey, $seq) : $childKey;
$node->addChild($child, $newKey);
self::reindexTree($child, $key, $sort);
$seq += 1;
}
}

/**
* @internal
*/
Expand Down
Loading

0 comments on commit 0e997f7

Please sign in to comment.