Advertisement
Guest User

Untitled

a guest
Sep 29th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. /**
  3.  * A n-dimensional arithmetic encoder. Provides
  4.  * indexing services for non-linear multi dimentional
  5.  * arrays.
  6.  */
  7. export class Encoder {
  8.  
  9.   /**
  10.    * creates a new encoder with the given bounds.
  11.    * @param {Array<number>} the dimensions of this encoder.
  12.    * @returns {Encoder}
  13.    */
  14.   constructor(public bounds: Array<number>) {}
  15.  
  16.   /**
  17.    * returns the linear length / size of memory
  18.    * addressable by this encoder.
  19.    * @returns {number}
  20.    */
  21.   public length(): number {
  22.     return this.bounds.reduce((acc, n) => acc * n, 1)
  23.   }
  24.  
  25.   /**
  26.    * for the given linear offset, return the n-dimensional address.
  27.    * @param {number} the linear offset.
  28.    * @returns {Array<number>}
  29.    */
  30.   public address(offset: number) : Array<number> {
  31.     return this.bounds.reduce<[number[], number]>((state, rank, index) => {
  32.         state[0][index] = Math.floor(offset / state[1] % rank)
  33.         state[1] *= rank
  34.         return state
  35.     }, [new Array<number>(this.bounds.length), 1])[0]    
  36.   }
  37.  
  38.   /**
  39.    * for the given n-dimensional address, return the linear offset.
  40.    * @param {Array<number>} the n-dimentional address.
  41.    * @returns {number}
  42.    */
  43.   public offset(address: Array<number>) : number {
  44.     return this.bounds.reduce((state, rank, index) => {
  45.         state[0] += (address[index] * state[1])
  46.         state[1] *= rank
  47.         return state
  48.     }, [0, 1])[0]
  49.   }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement