From a72783156744869a3fa03681608a8be0ea4231f4 Mon Sep 17 00:00:00 2001 From: Colin Eberhardt Date: Tue, 24 Jun 2014 10:02:26 +0100 Subject: [PATCH] Added a sortBy method --- ExSwift/Array.swift | 13 +++++++++++++ ExSwiftTests/ExSwiftArrayTests.swift | 10 ++++++++++ README.md | 1 + 3 files changed, 24 insertions(+) diff --git a/ExSwift/Array.swift b/ExSwift/Array.swift index 580edad..9c4dfe4 100644 --- a/ExSwift/Array.swift +++ b/ExSwift/Array.swift @@ -664,6 +664,19 @@ extension Array { return result } + + /** + * Sorts the array by the given comparison function + * @param isOrderedBefore + * @return An array that is sorted by the given function + */ + func sortBy (isOrderedBefore: (T, T) -> Bool) -> Array { + var clone = self + clone.unshare() + clone.sort(isOrderedBefore) + return clone + } + /** * Removes the last element from self and returns it diff --git a/ExSwiftTests/ExSwiftArrayTests.swift b/ExSwiftTests/ExSwiftArrayTests.swift index cc93766..89ae8f3 100644 --- a/ExSwiftTests/ExSwiftArrayTests.swift +++ b/ExSwiftTests/ExSwiftArrayTests.swift @@ -17,6 +17,16 @@ class ExtensionsArrayTests: XCTestCase { array = [1, 2, 3, 4, 5] } + func testSortBy () { + var sourceArray = [2,3,6,5] + var sortedArray = sourceArray.sortBy {$0 < $1} + + // check that the source array as not been mutated + XCTAssertEqualObjects(sourceArray, [2, 3, 6, 5]) + // check that the destination has been sorted + XCTAssertEqualObjects(sortedArray, [2, 3, 5, 6]) + } + func testReject () { var odd = array.reject({ return $0 % 2 == 0 diff --git a/README.md b/README.md index 34917f1..feb1a46 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ Name | Signature **`reduceRight`**|`reduceRight (initial: U, combine: (U, Element) -> U) -> U` **`implode`**|`implode (separator: C) -> C?` **`flatten`**|`flatten () -> OutType[]` +**`sortBy`**|`sortBy (isOrderedBefore: (T, T) -> Bool) -> Array ` #### Class Methods ####