Skip to content

Commit

Permalink
- Added the Array and Hash .fetch() methods to fetch a value with a…
Browse files Browse the repository at this point in the history
… default value.

Example:
	var a = [3,9,27]
	say a.fetch(2, 42);	# fetches index 2 and prints: 27
	say a.fetch(3, 42);	# fails to fecth index 3, therefore prints: 42
  • Loading branch information
trizen committed Nov 23, 2015
1 parent 451f169 commit 5edff8a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/Sidef/Types/Array/Array.pm
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,11 @@ package Sidef::Types::Array::Array {
exists($self->[$index]) ? $self->[$index] : ();
}

sub fetch {
my ($self, $index, $default) = @_;
exists($self->[$index]) ? $self->[$index] : $default;
}

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

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

sub fetch {
my ($self, $key, $default) = @_;
exists($self->{$key}) ? $self->{$key} : $default;
}

sub slice {
my ($self, @keys) = @_;
$self->new(map { ($_ => exists($self->{$_}) ? $self->{$_} : undef) } @keys);
Expand Down

0 comments on commit 5edff8a

Please sign in to comment.