Skip to content
This repository has been archived by the owner on Mar 29, 2018. It is now read-only.

Commit

Permalink
Merge pull request #37 from michaeleisel/added_minBy_and_maxBy_methods
Browse files Browse the repository at this point in the history
Added minBy and maxBy methods
  • Loading branch information
pNre committed Nov 6, 2014
2 parents ad3f393 + 68af286 commit c8d9140
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
50 changes: 50 additions & 0 deletions ExSwift/Array.swift
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,56 @@ internal extension Array {

}

/**
The value for which call(value) is highest.

:returns: Max value in terms of call(value)
*/
func maxBy <U: Comparable> (call: (Element) -> (U)) -> Element? {

if let firstValue = self.first {
var maxElement: T = firstValue
var maxValue: U = call(firstValue)
for i in 1..<self.count {
let element: Element = self[i]
let value: U = call(element)
if value > maxValue {
maxElement = element
maxValue = value
}
}
return maxElement
} else {
return nil
}

}

/**
The value for which call(value) is lowest.

:returns: Min value in terms of call(value)
*/
func minBy <U: Comparable> (call: (Element) -> (U)) -> Element? {

if let firstValue = self.first {
var maxElement: T = firstValue
var minValue: U = call(firstValue)
for i in 1..<self.count {
let element: Element = self[i]
let value: U = call(element)
if value < minValue {
maxElement = element
minValue = value
}
}
return maxElement
} else {
return nil
}

}

/**
Iterates on each element of the array.

Expand Down
24 changes: 24 additions & 0 deletions ExSwiftTests/ExSwiftArrayTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,28 @@ class ExtensionsArrayTests: XCTestCase {
let array1 = ["zero", "one", "two", "three"][rangeAsArray: 1...3]
let array2 = ["zero", "one", "two", "three"][rangeAsArray: 1..<3]
}

func testMinBy() {
var minValue: Int?
minValue = array.minBy({ -$0 })
XCTAssertEqual(minValue!, 5)
minValue = array.minBy({ $0 % 4 })
XCTAssertEqual(minValue!, 4)
minValue = array.minBy({ $0 })
XCTAssertEqual(minValue!, 1)
minValue = array.minBy({ $0 % 2 })
XCTAssertTrue(minValue! == 2 || minValue! == 4) // it's a tie
}

func testMaxBy() {
var maxValue: Int?
maxValue = array.maxBy({ -$0 })
XCTAssertEqual(maxValue!, 1)
maxValue = array.maxBy({ $0 % 4 })
XCTAssertEqual(maxValue!, 3)
maxValue = array.maxBy({ $0 })
XCTAssertEqual(maxValue!, 5)
maxValue = array.maxBy({ $0 % 3 })
XCTAssertTrue(maxValue! == 2 || maxValue! == 5) // it's a tie
}
}

0 comments on commit c8d9140

Please sign in to comment.