Skip to content

Commit

Permalink
- Added the Array.map_with_index{} method
Browse files Browse the repository at this point in the history
new file:   scripts/Tests/word_processing.sf
  • Loading branch information
trizen committed Nov 15, 2015
1 parent 11fa219 commit 3ae5182
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions MANIFEST
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,7 @@ scripts/Tests/vigenere_cipher.sf
scripts/Tests/virtual_machine.sf
scripts/Tests/while_loop.sf
scripts/Tests/wireworld.sf
scripts/Tests/word_processing.sf
scripts/Tests/word_roots.sf
scripts/tree_traversal.sf
scripts/unique_prefixes.sf
Expand Down
12 changes: 11 additions & 1 deletion lib/Sidef/Types/Array/Array.pm
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,17 @@ package Sidef::Types::Array::Array {

*collect = \↦

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

my @arr;
foreach my $i (0 .. $#{$self}) {
push @arr, $code->run(Sidef::Types::Number::Number->new($i), $self->[$i]);
}

$self->new(@arr);
}

sub flat_map {
my ($self, $code) = @_;
$self->new(map { @{scalar $code->run($_)} } @{$self});
Expand Down Expand Up @@ -816,7 +827,6 @@ package Sidef::Types::Array::Array {

my @sorted = do {
my @arr;

foreach my $i (0 .. $#{$self}) {
push @arr, [$i, $self->[$i]];
}
Expand Down
17 changes: 17 additions & 0 deletions scripts/Tests/word_processing.sf
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/usr/bin/ruby

var base = ('A'.ord - 1);

var n = DATA.slurp.chomp.split(/\s*,\s*/)
.map { |s| s - /"/g }.sort.uniq
.map { |s| s.chars.map { |sym| sym.ord - base }.sum }
.map_with_index { |idx, val| val * (idx+1) }
.sum;

assert_eq(n, 5738);
say "** Test passed!";

__DATA__
"LISA","MARY","PATRICIA","LINDA","BARBARA",
"MARIA","ELIZABETH","JENNIFER","MARIA","SUSAN",
"MARGARET","DOROTHY","LISA","NANCY","KAREN","MARY"

0 comments on commit 3ae5182

Please sign in to comment.