Skip to content

Commit

Permalink
- Added the Array and Hash .dig() method.
Browse files Browse the repository at this point in the history
Example:
	say data.dig(:users, 0, :name);

is equivalent with:
	say data{:users}[0]{:name}

but it simply returns `nil` when it fails to `.fetch()` a given value from an object.
  • Loading branch information
trizen committed Nov 26, 2015
1 parent 4f66979 commit 6ce5ad5
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions MANIFEST
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,7 @@ scripts/Tests/count_in_factors.sf
scripts/Tests/cpp_input_output.sf
scripts/Tests/cramers_method.sf
scripts/Tests/cross_and_zip_metaoperators.sf
scripts/Tests/data_digging.sf
scripts/Tests/data_handle.sf
scripts/Tests/default_param_values.sf
scripts/Tests/default_var_values.sf
Expand Down
12 changes: 12 additions & 0 deletions lib/Sidef/Types/Array/Array.pm
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,18 @@ package Sidef::Types::Array::Array {
exists($self->[$index]) ? $self->[$index] : $default;
}

sub dig {
my ($self, $key, @keys) = @_;

my $value = $self->fetch($key) // return;

foreach my $key (@keys) {
$value = $value->fetch($key) // return $value;
}

$value;
}

sub _slice {
my ($self, $from, $to) = @_;

Expand Down
12 changes: 12 additions & 0 deletions lib/Sidef/Types/Hash/Hash.pm
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ package Sidef::Types::Hash::Hash {
exists($self->{$key}) ? $self->{$key} : $default;
}

sub dig {
my ($self, $key, @keys) = @_;

my $value = $self->fetch($key) // return;

foreach my $key (@keys) {
$value = $value->fetch($key) // return;
}

$value;
}

sub slice {
my ($self, @keys) = @_;
$self->new(map { ($_ => exists($self->{$_}) ? $self->{$_} : undef) } @keys);
Expand Down
29 changes: 29 additions & 0 deletions scripts/Tests/data_digging.sf
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#!/usr/bin/ruby

var data = Hash(
lang => [
Hash(
name => "Sidef"
),
Hash(
name => "Ruby",
),
Hash(
name => "Perl",
)
]
)

say data.dig(:lang, 0, :name);
say data.dig(:lang, 1, :name);
say data.dig(:lang, 2, :name);

# Successful digging
assert_eq(data.dig(:lang, 0, :name), "Sidef");
assert_eq(data{:lang}.dig(-1, :name), "Perl");
assert_eq(data{:lang}[1].dig(:name), "Ruby");

# Fail digging
assert_eq(data.dig(:lang, 42, :name), nil);
assert_eq(data.dig(:hello, 0, :name), nil);
assert_eq(data{:lang}.dig(42, :name), nil);

0 comments on commit 6ce5ad5

Please sign in to comment.