Skip to content

Commit

Permalink
Update NaryNode - make it simpler and cleaner.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed May 2, 2019
1 parent d8d70f7 commit bb6e292
Showing 1 changed file with 21 additions and 29 deletions.
50 changes: 21 additions & 29 deletions src/Node/NaryNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
/**
* Class NaryNode.
*/
class NaryNode extends Node
class NaryNode extends Node implements NaryNodeInterface
{
/**
* The capacity of a node, the maximum children a node can have.
Expand Down Expand Up @@ -53,9 +53,25 @@ public function __construct(int $capacity = 0, NodeInterface $parent = null, Tra
public function add(NodeInterface ...$nodes): NodeInterface
{
foreach ($nodes as $node) {
/** @var \drupol\phptree\Node\Node $parent */
$parent = $this->findFirstAvailableNode();
$parent->storage['children'][] = $node->setParent($parent);
if (0 === $this->capacity() || ($this->degree() < $this->capacity())) {
parent::add($node);

continue;
}

foreach ($this->traverser->traverse($this) as $candidate) {
if (!($candidate instanceof NaryNodeInterface)) {
continue;
}

if ($candidate->degree() >= $candidate->capacity()) {
continue;
}

$candidate->add($node);

break;
}
}

return $this;
Expand All @@ -72,32 +88,8 @@ public function capacity(): int
/**
* {@inheritdoc}
*/
public function getTraverser()
public function getTraverser(): TraverserInterface
{
return $this->traverser;
}

/**
* Find first node in the tree that could have a new children.
*
* @return \drupol\phptree\Node\NodeInterface
*/
private function findFirstAvailableNode(): NodeInterface
{
$capacity = $this->capacity();

foreach ($this->getTraverser()->traverse($this) as $node) {
if (\method_exists($node, 'capacity')) {
$capacity = $node->capacity();
}

if ($node->degree() >= $capacity) {
continue;
}

return $node;
}

return $this;
}
}

0 comments on commit bb6e292

Please sign in to comment.