From 7ee5be674d9456f15ea419fc9a69ee3b635fcc17 Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Sat, 2 Jan 2010 00:20:24 -0500 Subject: [PATCH] adding splice literals, with tests --- lib/coffee_script/nodes.rb | 16 ++++++++++++++-- test/fixtures/execution/test_splices.coffee | 5 +++++ 2 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 test/fixtures/execution/test_splices.coffee diff --git a/lib/coffee_script/nodes.rb b/lib/coffee_script/nodes.rb index 2ea0a336..29ab1aa1 100644 --- a/lib/coffee_script/nodes.rb +++ b/lib/coffee_script/nodes.rb @@ -294,8 +294,10 @@ module CoffeeScript end def compile(o={}) - o = super(o) - parts = [@literal, @properties].flatten.map do |val| + o = super(o) + only = o.delete(:only_first) + props = only ? @properties[0...-1] : @properties + parts = [@literal, props].flatten.map do |val| val.respond_to?(:compile) ? val.compile(o) : val.to_s end @last = parts.last @@ -413,6 +415,7 @@ module CoffeeScript def compile(o={}) o = super(o) + return compile_splice(o) if @variable.properties.last.is_a?(SliceNode) name = @variable.compile(o) last = @variable.last.to_s.sub(LEADING_DOT, '') proto = name[PROTO_ASSIGN, 1] @@ -424,6 +427,15 @@ module CoffeeScript val = "#{name} = #{@value.compile(o)}" write(o[:return] && !@value.custom_return? ? "#{o[:indent]}return (#{val})" : val) end + + def compile_splice(o) + var = @variable.compile(o.merge(:only_first => true)) + range = @variable.properties.last.range + plus = range.exclusive? ? '' : ' + 1' + from = range.from.compile(o) + to = "#{range.to.compile(o)} - #{from}#{plus}" + write("#{var}.splice.apply(#{var}, [#{from}, #{to}].concat(#{@value.compile(o)}))") + end end # Simple Arithmetic and logical operations. Performs some conversion from diff --git a/test/fixtures/execution/test_splices.coffee b/test/fixtures/execution/test_splices.coffee new file mode 100644 index 00000000..0ac1135f --- /dev/null +++ b/test/fixtures/execution/test_splices.coffee @@ -0,0 +1,5 @@ +array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + +array[5..10]: [0, 0, 0] + +print(array.join(' ') is '0 1 2 3 4 0 0 0') \ No newline at end of file