Skip to content

Commit

Permalink
add sort_by macro method
Browse files Browse the repository at this point in the history
  • Loading branch information
Joakim Reinert committed Jan 27, 2017
1 parent 15032cc commit 3fdd401
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions spec/compiler/macro/macro_methods_spec.cr
Expand Up @@ -601,6 +601,10 @@ describe "macro methods" do
assert_macro "", %({{["c".id, "b", "a".id].sort}}), [] of ASTNode, %([a, "b", c])
end

it "executes sort_by" do
assert_macro "", %({{["abc", "a", "ab"].sort_by { |x| x.size }}}), [] of ASTNode, %(["a", "ab", "abc"])
end

it "executes uniq" do
assert_macro "", %({{[1, 1, 1, 2, 3, 1, 2, 3, 4].uniq}}), [] of ASTNode, %([1, 2, 3, 4])
end
Expand Down
19 changes: 19 additions & 0 deletions src/compiler/crystal/macros/methods.cr
Expand Up @@ -1889,6 +1889,12 @@ private def intepret_array_or_tuple_method(object, klass, method, args, block, i
klass.new(object.elements.shuffle)
when "sort"
klass.new(object.elements.sort { |x, y| x.interpret_compare(y) })
when "sort_by"
object.interpret_argless_method(method, args) do
raise "reject expects a block" unless block

sort_by(object, klass, block, interpreter)
end
when "uniq"
klass.new(object.elements.uniq)
when "[]"
Expand Down Expand Up @@ -2005,3 +2011,16 @@ def filter(object, klass, block, interpreter, keep = true)
keep ? block_result : !block_result
})
end

private def sort_by(object, klass, block, interpreter)
block_arg = block.args.first?

klass.new(object.elements.sort { |x, y|
block_arg.try { |arg| interpreter.define_var(arg.name, x) }
x_result = interpreter.accept(block.body)
block_arg.try { |arg| interpreter.define_var(arg.name, y) }
y_result = interpreter.accept(block.body)

x_result.interpret_compare(y_result)
})
end

0 comments on commit 3fdd401

Please sign in to comment.