All files reduce.ts

100% Statements 12/12
100% Branches 2/2
100% Functions 1/1
100% Lines 11/11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 2613x                   8x 8x 12x 12x 6x 6x   6x   12x   8x     13x  
import { Collection, asIterable } from './utils'
import Sequence from './Sequence'
 
/**
 * Apply a function against an accumulator and each element of the Collection to reduce it to a single value.
 * @param collection A Collection whose elements will be reduces to a single value.
 * @param fn A function that uses an accumulator and an element and reduces them to a single value.
 */
function reduce<T>(collection: Collection<T>, fn: (accumulator: T, value: T, index: number) => T) {
  let accumulator
  let isFirstElement = true
  let index = 0
  for(const value of asIterable(collection)) {
    if(isFirstElement) {
      accumulator = value
      isFirstElement = false
    } else {
      accumulator = fn(<T>accumulator, value, index)
    }
    index++
  }
  return accumulator
}
 
export default reduce