Skip to content

Commit

Permalink
- Added the Array.each_cons(n, { ... }) method to iterate over n cons…
Browse files Browse the repository at this point in the history
…ecutive values at a time.

Example:
	[1,2,3,4,5,5,7].each_cons(3, {|slice|  say slice })

Outputs:

[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
  • Loading branch information
trizen committed Dec 20, 2015
1 parent 2410abe commit 203ce65
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion bin/sidef
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ sub output_usage {
'-v' => 'print version number and exit',
'-t' => 'treat all command-line arguments as scripts',
'-r' => 'parse and deparse a Sidef program',
'-R lang' => ['parse and deparse a Sidef program to a given language',
'-R lang' => ['parse and deparse a Sidef program into a given language',
'valid values: sidef, perl'],
'-w' => 'enable warnings with stack backtrace',
'-W' => 'make warnings fatal (with stack backtrace)',
Expand Down
18 changes: 18 additions & 0 deletions lib/Sidef/Types/Array/Array.pm
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,24 @@ package Sidef::Types::Array::Array {
$self;
}

sub each_cons {
my ($self, $n, $code) = @_;

{
local $Sidef::Types::Number::Number::GET_PERL_VALUE = 1;
$n = $n->get_value;
}

my $end = @{$self};
foreach my $i ($n - 1 .. $end - 1) {
if (defined(my $res = $code->_run_code($self->new(@{$self}[$i - $n + 1 .. $i])))) {
return $res;
}
}

$self;
}

sub each_index {
my ($self, $code) = @_;

Expand Down

0 comments on commit 203ce65

Please sign in to comment.