All files index.ts

100% Statements 44/44
100% Branches 16/16
100% Functions 9/9
100% Lines 34/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            1x 27x   49x 27x     1x 51x     1x 1x     1x 9x     1x 5x     1x 11x 2x     9x 4x     5x     36x 9x 9x     1x 72x 117x 117x 2x   115x 54x 54x   61x 36x 36x   25x       1x  
export interface Options {
  keys?: string[] // only these keys will be transposed
}
 
export type Transposed<T> = { [key: string]: { [key: string]: [T] } }
 
export class OatyArray<T = any> {
  private _transposed: Transposed<T> = {}
 
  constructor(private _data: T[] = [], private _options: Options = {}) {
    this.transpose(_data)
  }
 
  get keys(): string[] | undefined {
    return this._options.keys
  }
 
  get length(): number {
    return this._data.length
  }
 
  get data(): T[] {
    return this._data
  }
 
  get transposed(): Transposed<T> {
    return this._transposed
  }
 
  public get(keyName: string, keyValue?: string): { [key: string]: [T] } | T[] | undefined {
    if (this._transposed[keyName] === undefined) {
      throw new ReferenceError(`The key '${keyName}' has not been transposed`)
    }
 
    if (keyValue === undefined) {
      return this._transposed[keyName]
    }
 
    return this._transposed[keyName][keyValue]
  }
 
  public push(...data: T[]) {
    this.transpose(data)
    return this._data.push(...data)
  }
 
  private transpose(data: T[]) {
    for (const datum of data) {
      for (const key of (this.keys || Object.keys(datum))) {
        if (datum[key] === undefined) {
          continue
        }
        if (this._transposed[key] === undefined) {
          this._transposed[key] = {[datum[key]]: [datum]}
          continue
        }
        if (this._transposed[key][datum[key]] === undefined) {
          this._transposed[key][datum[key]] = [datum]
          continue
        }
        this._transposed[key][datum[key]].push(datum)
      }
    }
  }
}