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

mapAccum for Array #60

Merged
merged 1 commit into from
Jan 11, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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