Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Collection<T>

Collection of elements with type T with many helpful methods

Type parameters

  • T

    Type of elements that collection will be include

Hierarchy

Index

Constructors

constructor

  • new Collection(initItems?: Array<T>): Collection
  • Creates new collection

    const nums: Collection<number> = new Collection()
    nums.push( 1 )
    
    const vegetables = new Collection( [ {
      name: 'potato',
      cost: 20
    }, {
      name: 'squash',
      cost: 31
    } ] )
    

    Parameters

    • Optional initItems: Array<T>

    Returns Collection

Accessors

length

  • get length(): number
  • Items count

    const vec = new Collection( [ [], [] ] )
    assert( vec.length === 2 )
    vec.clear()
    assert( vec.length === 0 )

    Returns number

Methods

chunks

  • chunks(chunkSize: number): Array<Array<T>>

clear

  • clear(): void
  • Clears the collection, removing all values

    const vec = new Collection( [ 3, 2, 1 ] )
    vec.clear()
    assert( vec.isEmpty() )

    Returns void

drainFilterBy

  • For all elements calls a provided function to determine if an element should be removed from collection. Works in place and returns Array of removed elements.

    const nums = new Collection( [ 1, 79, 5, 42, 3 ] )
    const _removed = nums.drainFilterBy( ( n ) => n > 10 )
    
    assert( nums.length === 3 && nums.last() === 3 )
    assert( _removed.length === 2 && _removed.first() === 79 )

    Parameters

    Returns Array<T>

filterBy

  • Creates new instance of current type of collection only with elements that pass the test implemented by the provided function. Similar to Array.prototype.filter

    const arrays = new Collection( [ [], [ 5 ], [] ] )
    const nonEmptyArrays = arrays.filterBy( ( arr: number[] ): boolean => arr.length !== 0 )
    
    assert( nonEmptyArrays.length === 1 )
    assert( nonEmptyArrays.first()[ 0 ] === 5 )

    Parameters

    Returns this

findBy

  • findBy(predicate: CallbackFuncType<T, boolean>, startIndex?: undefined | number): null | T
  • Searches for an element that satisfies a predicate
    Takes a closure that returns boolean. It applies this closure to each element of the collection, and if any of them return true, then findBy() returns element. If they all return false, it returns null

    const nums = new Collection( [ 1, 2, 3 ] )
    const one = nums.find( ( n: number ): boolean => n === 1 )
    assert( one === 1 )
    const ten = nums.find( n => n === 10 )
    assert( ten === null )
    
    type Tree = { name: string }
    const trees = new Collection<Tree>( [ { name: 'spruce' }, { name: 'pine' }, { name: 'poplar' } ] )
    const pine = trees.find( ( t: Tree ): boolean => t.name === 'pine' )
    assert( pine && pine.name === 'pine' )
    const pineAtTheEnd = trees.find( t => t.name === 'pine', 2 )
    assert( pine === null )

    Parameters

    • predicate: CallbackFuncType<T, boolean>

      Predicate

    • Optional startIndex: undefined | number

      The position where to start searching

    Returns null | T

findIndexBy

  • findIndexBy(predicate: CallbackFuncType<T, boolean>, startIndex?: undefined | number): number
  • Searches for an index of element that satisfies a predicate
    Like findBy but returns index

    const nums = new Collection( [ 1, 2, 3 ] )
    const oneInd = nums.find( ( n: number ): boolean => n === 1 )
    assert( oneInd === 0 )
    const tenInd = nums.find( n => n === 10 )
    assert( tenInd === -1 )
    
    const trees = new Collection<Tree>( [ { name: 'spruce' }, { name: 'poplar' } ] )
    const poplarInd = trees.find( t => t.name === 'poplar' )
    assert( poplarInd  === -1 )

    Parameters

    • predicate: CallbackFuncType<T, boolean>

      Predicate

    • Optional startIndex: undefined | number

      The position where to start searching

    Returns number

first

  • first(): null | T
  • Returns the first element of the collection, or null if it is empty

    const coll = new Collection( [ 'a', 'b', 'c' ] )
    assert( coll.first() === 'a' )
    
    coll.clear()
    assert( coll.first() === null )

    Returns null | T

forEach

  • Calls a closure on each element of an collection.

    interface Counter {
      count: number;
      increment(): void;
    }
    
    const vec: Collection<Counter> = new Collection()
    const c: Counter = {
      count: 0,
      increment: function() {
        this.count++
      }
    }
    vec.push( c )
    vec.forEach( c => c.increment() )
    
    assert( vec.first().count === 1 )

    Parameters

    • closure: CallbackFuncType<T, void>

      Callback which will be called on each element

    Returns void

get

  • get(index: number): null | T
  • Returns an element at the given position or null

    Parameters

    • index: number

      Index

      const coll = new Collection( [ 'a', 'b', 'c' ] )
      assert( coll.get( 2 ) === 'c' )
      assert( coll.get( 12 ) === null )

    Returns null | T

getInnerRef

  • getInnerRef(): Array<T>
  • Returns reference to inner array of elements

    const vec = new Collection( [ 0, 9, 8 ] )
    const inner = vec.getInnerRef()
    assert( inner[ 2 ] === 8 )
    vec.clear()
    assert( inner[ 0 ] === undefined )
    assert( inner === vec.getInnerRef() )

    Returns Array<T>

has

  • has(it: T): boolean
  • Returns true if the collection contains an element which is the same as the given value. Uses strict comparison

    const vec = new Collection( [ 7, 8, 9 ] )
    assert( vec.has( 8 ) )
    assert( !vec.has( 10 ) )
    
    const car1 = { name: 'UAZ' }
    const cars = new Collection( [ car1, { name: 'Toyota' }] )
    assert( cars.has( { name: 'Toyota' } ) === false )
    assert( cars.has( car1 ) === true )

    Parameters

    • it: T

      Item which is searching for

    Returns boolean

isEmpty

  • isEmpty(): boolean
  • Returns true if the collection contains no elements

    const vec = new Collection( [ [], [] ] )
    assert( !vec.isEmpty() )
    vec.clear()
    assert( vec.isEmpty() )

    Returns boolean

last

  • last(): null | T
  • Returns the last element of the collection, or null if it is empty

    const coll = new Collection( [ 'a', 'b', 'c' ] )
    assert( coll.last() === 'c' )
    
    coll.clear()
    assert( coll.last() === null )

    Returns null | T

lastIndex

  • lastIndex(): number
  • Returns index of last element or -1

    const vec = new Collection()
    assert( vec.lastIndex() === -1 )
    
    vec.push( [ 2, 3 ] )
    assert( vec.lastIndex() === 1 )
    assert( vec.lastIndex() === ( vec.length - 1 ) )

    Returns number

map

  • Produces a new instance of current type of collection by calling given closure on each element of the original collection and yielding return values of this closure

    const coll = new Collection<number>( [ 1, 2 ] )
    const doubleStrColl = coll.map( ( n: number ): string => ( n * 2 ).toString() )
    
    assert( doubleStrColl.first() === '2' )
    assert( doubleStrColl.last() === '4' )
    
    const indexes = new Collection([ { i: 1, i: 3 } ] )
    const indexesRenamed = indexes.map( ( item ) => ( { index: item.i } ) )
    assert( indexesRenamed.first().index === 1 )
    assert( indexesRenamed.first().i === undefined )

    Type parameters

    • R

      Return type of the callback and consequently type of items in generated collection

    Parameters

    Returns Collection<R>

mapArr

  • Produces a new Array<R> by calling given closure on each element of the original collection and collecting return values of this closure Like map but returns Array instead of collection

    const coll = new Collection<number>( [ 1, 2 ] )
    const doubleStrArr = coll.mapArr( ( n: number ): string => ( n * 2 ).toString() )
    assert( doubleStrArr[ 0 ] === '2' )
    assert( doubleStrArr[ 1 ] === '4' )
    
    const towns = new Collection( [ { name: 'Sydney' }, { name: 'Baghdad' } ] )
    const names = towns.mapArr( t => t.name )
    assert( names.length === 2 && names[ 1 ] === 'Baghdad' )

    Type parameters

    • R

      Return type of the callback and consequently type of items in generated array

    Parameters

    Returns Array<R>

pop

  • pop(): null | T
  • Removes the last element from the collection and returns it. Or return null if collection is empty

    const chars = new Collection( [ 'o', 'p', 'q' ] )
    const last = chars.pop()
    assert( last === 'q' )
    assert( chars.length === 2 ) // [ 'o', 'p' ]

    Returns null | T

push

  • push(it: T | Array<T>): void
  • Appends an element(s) to the back of a collection

    const vec = new Collection( [ 'd', 'e', 'w' ] )
    assert( vec.last() === 'w' )
    vec.push( 'a' )
    assert( vec.last() === 'a' )
    vec.push( [ 'x', 'y', 'z' ] )
    assert( vec.length === 7 )

    Parameters

    • it: T | Array<T>

      Element or array of elements to append

    Returns void

pushUniq

  • pushUniq(it: T | Array<T>): void
  • Appends an element(s) to the back of a collection only if element is not exists in collection
    Uses simple strict comparison ( itemA === itemB ) for checking

    const nums = new Collection( [ 1, 2, 3 ] )
    nums.pushUniq( [ 4, 3, 1, 5 ] ) // 3 and 1 will not be appended
    assert( nums.length === 5 )
    
    const trees = new Collection( [ { name: 'spruce' }, { name: 'pine' } ] )
    trees.pushUniq( [ { name: 'poplar' }, { name: 'spruce' } ] ) // all elements will be appended
    assert( trees.length === 4 )
    assert( trees.last().name === 'spruce' )

    Parameters

    • it: T | Array<T>

      Element or array of elements to append

    Returns void

pushUniqBy

  • Appends an element(s) to the back of a collection only if element is not exists in collection
    Uses given compare function to check existing. Comparator must return boolean
    If for some pair of elements (inner and given) compare function returns true, given element will not be added

    const nums = new Collection( [ 1, 2, 3 ] )
    
    nums.pushUniqBy(
      [ 4, 3, 1, 5 ],
      ( innerItem: number, externalItem: number ): boolean => innerItem === externalItem
    )
    // 3 and 1 will not be appended. For primitives this example is the same as `pushUniq`
    
    assert( nums.length === 5 )
    
    type Tree = { name: string }
    const trees = new Collection<Tree>( [ { name: 'spruce' }, { name: 'pine' } ] )
    trees.pushUniqBy( [ {
      name: 'poplar'
    }, {
      name: 'spruce'
    } ], ( itA: Tree, itB: Tree ): boolean => {
      return itA.name === itB.name
    } )
    // second spruce will not be added
    
    assert( trees.length === 3 )
    assert( trees.last().name === 'poplar' )

    Parameters

    • it: T | Array<T>

      Element or array of elements to append

    • compare: CompareFuncType<T>

      Callback that will be compare given elements and existing in collection elements. Must return boolean

    Returns void

reduce

  • reduce<A>(callback: (acc: A, it: T) => A, initValue: A): A
  • Type parameters

    • A

    Parameters

    • callback: (acc: A, it: T) => A
        • (acc: A, it: T): A
        • Parameters

          • acc: A
          • it: T

          Returns A

    • initValue: A

    Returns A

remove

  • remove(index: number): null | T
  • Removes and returns the element at position index within the vector

    const vec: Collection<string>  = new Collection( [ 'x', 'y', 'z' ] )
    const y = vec.remove( 1 )
    assert( y === 'y' && vec.length === 2 )
    const a = vec.remove( 5 )
    assert( a === null && vec.length === 2 )

    Parameters

    • index: number

      Index

    Returns null | T

removeBy

  • Searches for an element that satisfies a predicate. And if some is matches removes and returns it. Stops after first found element

    const vec = new Collection( [ [ 'a' ], [ 'b', 'c' ], [ 'd' ] ] )
    vec.removeBy( it => it.length === 2 ) // removes second array
    assert( vec.length === 2 )
    
    const first = vec.removeBy( it => it.length === 1 ) // removes just first array
    assert( first[ 0 ] === 'a' )
    assert( vec.length === 1 )

    Parameters

    Returns null | T

repeat

  • repeat(num: number): this
  • Creates a new collection by repeating all elements num times.

    const chars = new Collection( [ 'a', 'z' ] )
    const repeated = chars.repeat( 3 )
    assert.deepEqual( repeated.toArray(), [ 'a', 'z', 'a', 'z', 'a', 'z' ] )

    Parameters

    • num: number

    Returns this

reset

  • reset(data: null | Array<T>): void
  • Resets all items in collection

    • If given data is null it will be the same as clear
    • If data is Array, these items replace exist items
    const vec = new Collection( [ 'a', 'b', 'c' ] )
    vec.reset( [ 'x', 'y', 'z' ] )
    assert( vec.last() === 'z' && vec.first() === 'x' )
    
    vec.reset( null )
    assert( vec.isEmpty() )

    Parameters

    • data: null | Array<T>

    Returns void

retainBy

  • Retains only the elements specified by the predicate.

    In other words, remove all elements for which predicate return false. Like a {@link filter} but operates in place. Returns Array of removed elements.

    const nums = new Collection( [ 1, 79, 5, 42, 3 ] )
    nums.retainBy( ( n ) => n > 10 )
    
    assert( nums.length === 2 )
    assert( nums.first() === 79 && nums.last() === 42 )

    Parameters

    Returns Array<T>

rfindBy

  • rfindBy(predicate: CallbackFuncType<T, boolean>, startIndex?: undefined | number): null | T
  • Searches for an element in the collection from the right, returning it or null
    See findBy

    const arrays = new Collection( [ [ 'a' ], [ 'b', 'c' ], [ 'd' ] ] )
    const arrWithOneItem = arrays.rfindBy( a => a.length === 1 )
    assert( arrWithOneItem[ 0 ] === 'd' )

    Parameters

    • predicate: CallbackFuncType<T, boolean>

      Predicate

    • Optional startIndex: undefined | number

      The position where to start searching

    Returns null | T

rfindIndexBy

  • rfindIndexBy(predicate: CallbackFuncType<T, boolean>, startIndex?: undefined | number): number
  • Searches for an element in the collection from the right, returning its index or -1
    See findIndexBy

    const arrays = new Collection( [ [ 'a' ], [ 'b', 'c' ], [ 'd' ] ] )
    const arrWithOneItemIndex = arrays.rfindIndexBy( a => a.length === 1 )
    assert( arrWithOneItemIndex === 2 )

    Parameters

    • predicate: CallbackFuncType<T, boolean>

      Predicate

    • Optional startIndex: undefined | number

      The position where to start searching

    Returns number

set

  • set(index: number, it: T): boolean
  • Replaces element at the given position with new element
    If index is out of current collection range returns false

    const coll = new Collection( [ 'a', 'b', 'c' ] )
    coll.set( 0, 'x' )
    assert( coll.first() === 'x' )
    const isSetted = coll.set( 10, 'z' )
    assert( !isSetted && coll.length === 3 )

    Parameters

    • index: number

      Index

    • it: T

    Returns boolean

shift

  • shift(): null | T
  • Removes the first element from the collection and returns it. Or return null if collection is empty

    const chars = new Collection( [ 'o', 'p', 'q' ] )
    const first = chars.shift()
    assert( first === 'o' )
    assert( chars.length === 2 ) // [ 'p', 'q' ]

    Returns null | T

shuffle

  • shuffle(): void
  • Shuffles the collection by using Fisher-Yates algorithm.

    const vec = new Collection( [ 1, 2, 3 ] )
    vec.shuffle()
    assert( true ) // who knows in what sequence these numbers are now

    Returns void

swap

  • swap(indexA: number, indexB: number): boolean
  • Swaps two elements in the collection Returns false if indexA or indexB are out of bounds.

    const nums = new Collection( [ 1, 2, 3 ] )
    nums.swap( 0, 2 )
    assert( nums.first() === 3 && nums.last() === 1 )
    const isSwapped = nums.swap( 0, 4 )
    assert( isSwapped === false )

    Parameters

    • indexA: number

      index of the first element

    • indexB: number

      index of the second element

    Returns boolean

toArray

  • toArray(): Array<T>
  • Returns new array of existing elements, without deep copying

    const car = { id: 1, name: 'UAZ' }
    const vec = new Collection()
    vec.push( car )
    const arr = vec.toArray()
    assert( Array.isArray( arr ) )
    assert( arr[ 0 ] === car )

    Returns Array<T>

toJSON

  • toJSON(): null | string
  • Returns json string of inner array of elements. It is unlikely, but it is still possible that the JSON.stringify ends with an error, in that case toJSON will return null

    const colors = new Collection( [ 'red', 'green' ] )
    const json = colors.toJSON()
    assert( json === "[\"red\",\"green\"]" )

    Returns null | string

truncate

  • truncate(len: number): boolean
  • Shortens the collection, keeping the first len elements and dropping the rest. If len is greater than the vector's current length, this has no effect. Returns true if collection truncated.

    const chars = new Collection( [ 'a', 'b', 'c', 'd' ] )
    chars.truncate( 2 )
    assert.deepEqual( chars.toArray(), [ 'a', 'b' ] )

    Parameters

    • len: number

      Expected length of collection

    Returns boolean

Generated using TypeDoc