Skip to content

Commit

Permalink
Merge pull request #13 from davorg/8-get_relationship_ancestors-method
Browse files Browse the repository at this point in the history
Add get_relationship_ancestors() method
  • Loading branch information
davorg committed May 24, 2023
2 parents 48d5c33 + 8f5325c commit 5217287
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions Changes.md
Expand Up @@ -6,6 +6,7 @@

- Pod error
- IDs no longer need to be numbers
- Added `get_relationship_ancestors()` method

## [0.1.2] - 2023-05-23

Expand Down
34 changes: 34 additions & 0 deletions lib/Genealogy/Relationship.pm
Expand Up @@ -318,6 +318,40 @@ sub get_relationship_coords {
die "Can't work out the relationship.\n";
}

=head2 get_relationship_ancestors
Given two people, returns lists of people linking those two people
to their most recent common ancestor.
The return value is a reference to an array containing two array
references. The first references array contains the person1 and
all their ancestors up to an including the most recent common
ancestor. The second list does the same for person2.
=cut

sub get_relationship_ancestors {
my $self = shift;
my ($person1, $person2) = @_;

my $mrca = $self->most_recent_common_ancestor($person1, $person2)
or die "There is no most recent common ancestor\n";

my (@ancestors1, @ancestors2);

for ($person1, $self->get_ancestors($person1)) {
push @ancestors1, $_;
last if $_->id eq $mrca->id;
}

for ($person2, $self->get_ancestors($person2)) {
push @ancestors2, $_;
last if $_->id eq $mrca->id;
}

return [ \@ancestors1, \@ancestors2 ];
}

=head1 AUTHOR
Dave Cross <dave@perlhacks.com>
Expand Down
10 changes: 10 additions & 0 deletions t/02-ancestors.t
Expand Up @@ -108,4 +108,14 @@ is($rel->get_relationship($cousin, $father), 'Niece',
is($rel->get_relationship($father, $cousin), 'Uncle',
'Father is the uncle of the niece');

can_ok($rel, 'get_relationship_ancestors');
my $rels = $rel->get_relationship_ancestors($father, $cousin);
is(@$rels, 2, 'Correct number of items from get_relationship_ancestors()');
is(@{$rels->[0]}, 2, 'Correct number of items from get_relationship_ancestors()');
is(@{$rels->[1]}, 3, 'Correct number of items from get_relationship_ancestors()');
$mrca = $rel->most_recent_common_ancestor($father, $cousin);
is($rels->[0][0]->id, $father->id, 'Father is first');
is($rels->[0][-1]->id, $mrca->id, 'MRCA is last');
is($rels->[1][0]->id, $cousin->id, 'Cousin is first');
is($rels->[1][-1]->id, $mrca->id, 'MRCA is last');
done_testing;

0 comments on commit 5217287

Please sign in to comment.