Skip to content

Allow conversion of multiple << to multiple .push calls #224

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions lib/ruby2js/converter/send.rb
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,28 @@ class Converter
elsif method == :!~
put '!'; parse args.first; put '.test('; parse receiver; put ')'

elsif method == :<< and args.length == 1 and @state == :statement
parse receiver; put '.push('; parse args.first; put ')'
elsif method == :<<
if @state == :statement
# Handle chained << operations by converting them to push() method calls
current = receiver
operations = [args.first]

# Traverse the AST to collect all chained << operations
while current.type == :send && current.children[1] == :<<
operations.unshift(current.children[2])
current = current.children[0]
end

# Generate a series of push() calls for each operation in the chain
operations.each do |arg|
parse current ; put '.push(' ; parse arg ; put ')'
put '; ' unless arg == operations.last
end
else
# If not in statement context, fall back to original behavior
group_receiver ? group(receiver) : parse(receiver)
put " << " ; group_target ? group(args.first) : parse(args.first)
end

elsif method == :<=>
parse receiver; put ' < '; parse args.first; put ' ? -1 : '
Expand Down
8 changes: 6 additions & 2 deletions spec/transliteration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -364,12 +364,16 @@ def to_js( string, opts={} )
to_js('x = ()').must_equal 'var x = null'
end
end

describe 'array push' do
it "should convert << statements to .push calls" do
to_js( 'a << b' ).must_equal 'a.push(b)'
end


it "should convert multiple << statements to multiple .push calls" do
to_js( 'a << b << c << d << e' ).must_equal 'a.push(b); a.push(c); a.push(d); a.push(e)'
end

it "should leave << expressions alone" do
to_js( 'y = a << b' ).must_equal 'var y = a << b'
end
Expand Down