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 #60 from phatmann/mapAccum
Browse files Browse the repository at this point in the history
mapAccum for Array
  • Loading branch information
pNre committed Jan 11, 2015
2 parents 2c1ef77 + cc5da94 commit 337ccdf
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
21 changes: 21 additions & 0 deletions ExSwift/Array.swift
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,27 @@ internal extension Array {

}

/**
Creates an array with values and an accumulated result by running accumulated result
and each value of self through the mapFunction.

:param: initial Initial value for accumulator
:param: mapFunction
:returns: Accumulated value and mapped array
*/
func mapAccum <U, V> (initial: U, mapFunction map: (U, Element) -> (U, V)) -> (U, [V]) {
var mapped = [V]()
var acc = initial

each { (value: Element) -> Void in
let (mappedAcc, mappedValue) = map(acc, value)
acc = mappedAcc
mapped.append(mappedValue)
}

return (acc, mapped)
}

/**
self.reduce with initial value self.first()
*/
Expand Down
9 changes: 9 additions & 0 deletions ExSwiftTests/ExSwiftArrayTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,15 @@ class ExtensionsArrayTests: XCTestCase {
XCTAssertEqual(m, [2, 3, 4])
}

func testMapAccum() {
let m:(Int, [Int]) = array.mapAccum(0) { acc, value in
return (acc + value, value * 2)
}

XCTAssertEqual(m.0, 15)
XCTAssertEqual(m.1, [2, 4, 6, 8, 10])
}

func testSubscriptConflicts() {
let array1 = ["zero", "one", "two", "three"][rangeAsArray: 1...3]
let array2 = ["zero", "one", "two", "three"][rangeAsArray: 1..<3]
Expand Down

0 comments on commit 337ccdf

Please sign in to comment.