Permalink
Browse files

add Enumerable#sort: and fix Enumerable#sort_by:

  • Loading branch information...
1 parent 1336a6c commit a881c34b261ba98d22bc53b383de9dd198559009 @bakkdoor committed Dec 9, 2012
Showing with 34 additions and 11 deletions.
  1. +20 −8 lib/enumerable.fy
  2. +8 −3 tests/array.fy
  3. +6 −0 tests/enumerable.fy
View
@@ -786,20 +786,32 @@ class Fancy {
at: $ size random
}
- def sort_by: block {
+ def sort: comparison_block {
"""
- @block @Block@ taking 2 arguments used to compare elements in a collection.
+ @comparison_block @Block@ taking 2 arguments used to compare elements in a collection.
@return Sorted @Array@ of elements in @self.
Sorts a collection by a given comparison block.
"""
- if: (block is_a?: Symbol) then: {
- sort() |a b| {
- a receive_message: block . <=> (b receive_message: block)
- }
- } else: {
- sort(&block)
+ sort(&comparison_block)
+ }
+
+ def sort_by: block {
+ """
+ @block @Block@ taking 1 argument used to extract a value to use for comparison.
+ @return Sorted @Array@ of elements in @self based on @block.
+
+ Sorts a collection by calling a @Block@ with every element
+ and using the return values for comparison.
+
+ Example:
+ [\"abc\", \"abcd\", \"ab\", \"a\", \"\"] sort_by: @{ size }
+ # => [\"\", \"a\", \"ab\", \"abc\", \"abcd\"]
+ """
+
+ sort_by() |x| {
+ block call: [x]
}
}
View
@@ -525,15 +525,20 @@ FancySpec describe: Array with: {
arr is: [1,5,4,2,3]
}
- it: "sorts the array with a given comparison block" with: 'sort_by: when: {
+ it: "sorts the array with a given comparison block" with: 'sort: when: {
arr = [1,5,4,2,3]
sorted = [1,2,3,4,5]
- arr sort_by: |a b| { a <=> b } . is: sorted
+ arr sort: |a b| { a <=> b } . is: sorted
arr is: [1,5,4,2,3]
arr = [(1,2), (0,1), (3,0)]
sorted = [(3,0), (0,1), (1,2)]
- arr sort_by: |a b| { a second <=> (b second) } . is: sorted
+ arr sort: |a b| { a second <=> (b second) } . is: sorted
+ }
+
+ it: "sorts the array by a given block" with: 'sort_by: when: {
+ arr = [(1,2), (0,1), (3,0)]
+ sorted = [(3,0), (0,1), (1,2)]
arr sort_by: 'second . is: sorted
}
View
@@ -97,6 +97,12 @@ FancySpec describe: Fancy Enumerable with: {
"fabc" sorted? is: false
}
+ it: "sorts by a given block" with: 'sort_by: when: {
+ [[1,2], [1,2,3], [1], []] sort_by: @{ size } . is: [[], [1], [1,2], [1,2,3]]
+ [[1,2], [1,2,3], [1], []] sort_by: 'size . is: [[], [1], [1,2], [1,2,3]]
+ ["abc", "abcd", "ab", "a", ""] sort_by: @{ size } . is: ["", "a", "ab", "abc", "abcd"]
+ }
+
it: "splits a collection at an index" with: 'split_at: when: {
[] split_at: 0 . is: [[],[]]
[1] split_at: 0 . is: [[],[1]]

0 comments on commit a881c34

Please sign in to comment.