Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * A n-dimensional arithmetic encoder. Provides
- * indexing services for non-linear multi dimentional
- * arrays.
- */
- export class Encoder {
- /**
- * creates a new encoder with the given bounds.
- * @param {Array<number>} the dimensions of this encoder.
- * @returns {Encoder}
- */
- constructor(public bounds: Array<number>) {}
- /**
- * returns the linear length / size of memory
- * addressable by this encoder.
- * @returns {number}
- */
- public length(): number {
- return this.bounds.reduce((acc, n) => acc * n, 1)
- }
- /**
- * for the given linear offset, return the n-dimensional address.
- * @param {number} the linear offset.
- * @returns {Array<number>}
- */
- public address(offset: number) : Array<number> {
- return this.bounds.reduce<[number[], number]>((state, rank, index) => {
- state[0][index] = Math.floor(offset / state[1] % rank)
- state[1] *= rank
- return state
- }, [new Array<number>(this.bounds.length), 1])[0]
- }
- /**
- * for the given n-dimensional address, return the linear offset.
- * @param {Array<number>} the n-dimentional address.
- * @returns {number}
- */
- public offset(address: Array<number>) : number {
- return this.bounds.reduce((state, rank, index) => {
- state[0] += (address[index] * state[1])
- state[1] *= rank
- return state
- }, [0, 1])[0]
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement