All files Sequence.ts

100% Statements 46/46
100% Branches 8/8
100% Functions 11/11
100% Lines 40/40
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 697x 7x 7x 7x 7x 7x   7x       72x 51x 21x 10x   11x 2x 4x           7x 20x 75x 75x   20x     7x 2x 2x 6x 6x 2x 2x   4x     2x     7x 1x     7x 2x     7x 1x     7x 1x     7x 1x   7x   7x  
import { Collection, isIterable } from './utils'
import zip from './zip'
import repeat from './repeat'
import map from './map'
import flatMap from './flatMap'
import filter from './filter'
 
class Sequence<T> implements Iterable<T> {
  [Symbol.iterator]: () => Iterator<T>
 
  constructor(collection: Collection<T>) {
    if(typeof collection === 'function') {
      this[Symbol.iterator] = collection
    } else if(isIterable(collection)) {
      this[Symbol.iterator] = () => collection[Symbol.iterator]()
    } else {
      this[Symbol.iterator] = function* () {
        for(let i = 0; i < collection.length; i++) {
          yield collection[i]
        }
      }
    }
  }
 
  toArray() {
    const result = []
    for(const value of this) {
      result.push(value)
    }
    return result
  }
 
  join(separator = '') {
    let result = ''
    let first = true
    for(const value of this) {
      if(first) {
        result += value
        first = false
      } else {
        result += separator + value
      }
    }
    return result
  }
 
  zip<U>(collection: Collection<U>) {
    return zip(this, collection)
  }
 
  repeat(times?: number) {
    return repeat(this, times)
  }
 
  map<U>(fn: (value: T, index: number) => U) {
    return map(this, fn)
  }
 
  flatMap<U>(fn: (value: T, index: number) => Collection<U>) {
    return flatMap(this, fn)
  }
 
  filter(fn: (value: T, index: number) => boolean) {
    return filter(this, fn)
  }
}
 
export default Sequence