Skip to content

Commit

Permalink
Implement Enumerable#slice_before
Browse files Browse the repository at this point in the history
  • Loading branch information
meh committed Oct 28, 2013
1 parent 6d25a78 commit 365aed5
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
60 changes: 60 additions & 0 deletions corelib/enumerable.rb
Expand Up @@ -791,6 +791,66 @@ def one?(&block)
}
end

def slice_before(pattern = undefined, &block)
if `pattern === undefined && block === nil || arguments.length > 1`
raise ArgumentError, "wrong number of arguments (#{`arguments.length`} for 1)"
end

Enumerator.new {|e|
%x{
var slice = [];
if (block !== nil) {
if (pattern === undefined) {
self.$each._p = function() {
var param = #{Opal.destructure(`arguments`)},
value = $opal.$yield1(block, param);
if (#{Opal.truthy?(`value`)} && slice.length > 0) {
#{e << `slice`};
slice = [];
}
slice.push(param);
};
}
else {
self.$each._p = function() {
var param = #{Opal.destructure(`arguments`)},
value = block(param, #{pattern.dup});
if (#{Opal.truthy?(`value`)} && slice.length > 0) {
#{e << `slice`};
slice = [];
}
slice.push(param);
};
}
}
else {
self.$each._p = function() {
var param = #{Opal.destructure(`arguments`)},
value = #{pattern === `param`};
if (#{Opal.truthy?(`value`)} && slice.length > 0) {
#{e << `slice`};
slice = [];
}
slice.push(param);
};
}
self.$each();
if (slice.length > 0) {
#{e << `slice`};
}
}
}
end

def sort_by(&block)
return enum_for :sort_by unless block_given?

Expand Down
1 change: 1 addition & 0 deletions spec/rubyspecs
Expand Up @@ -127,6 +127,7 @@ core/enumerable/none_spec
core/enumerable/one_spec
core/enumerable/reduce_spec
core/enumerable/select_spec
core/enumerable/slice_before_spec
core/enumerable/sort_by_spec
core/enumerable/take_spec
core/enumerable/take_while_spec
Expand Down

0 comments on commit 365aed5

Please sign in to comment.