|
| 1 | +import { FastMap } from '../src/index'; |
| 2 | + |
| 3 | +describe('FastMap iteration', () => { |
| 4 | + it('entries() yields [[x,y], value] in row-major order', () => { |
| 5 | + const width = 3; |
| 6 | + const height = 2; |
| 7 | + const map = new FastMap<number>(width, height); |
| 8 | + |
| 9 | + // set a few values, leave others undefined |
| 10 | + map.Set(0, 0, 1); |
| 11 | + map.Set(2, 0, 2); |
| 12 | + map.Set(1, 1, 3); |
| 13 | + |
| 14 | + const entries = Array.from(map.entries()); |
| 15 | + expect(entries.length).toBe(width * height); |
| 16 | + |
| 17 | + // each entry should match map.Get(x,y) |
| 18 | + for (const [[x, y], value] of entries) { |
| 19 | + expect(map.Get(x, y)).toBe(value); |
| 20 | + } |
| 21 | + |
| 22 | + // check first and last coordinates |
| 23 | + expect(entries[0][0]).toEqual([0, 0]); |
| 24 | + expect(entries[0][1]).toBe(1); |
| 25 | + expect(entries[entries.length - 1][0]).toEqual([2, 1]); |
| 26 | + }); |
| 27 | + |
| 28 | + it('keys() yields coordinates in row-major order', () => { |
| 29 | + const width = 4; |
| 30 | + const height = 3; |
| 31 | + const map = new FastMap<number>(width, height); |
| 32 | + |
| 33 | + const keys = Array.from(map.keys()); |
| 34 | + expect(keys.length).toBe(width * height); |
| 35 | + |
| 36 | + let idx = 0; |
| 37 | + for (let y = 0; y < height; y++) { |
| 38 | + for (let x = 0; x < width; x++) { |
| 39 | + expect(keys[idx]).toEqual([x, y]); |
| 40 | + idx++; |
| 41 | + } |
| 42 | + } |
| 43 | + }); |
| 44 | + |
| 45 | + it('values() yields values in row-major order', () => { |
| 46 | + const width = 5; |
| 47 | + const height = 2; |
| 48 | + const map = new FastMap<number>(width, height); |
| 49 | + |
| 50 | + // initialize map with predictable values: value = y * width + x |
| 51 | + for (let y = 0; y < height; y++) { |
| 52 | + for (let x = 0; x < width; x++) { |
| 53 | + map.Set(x, y, y * width + x); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + const values = Array.from(map.values()); |
| 58 | + expect(values.length).toBe(width * height); |
| 59 | + |
| 60 | + for (let i = 0; i < values.length; i++) { |
| 61 | + expect(values[i]).toBe(i); |
| 62 | + } |
| 63 | + }); |
| 64 | + |
| 65 | + it('default iterator yields same as entries()', () => { |
| 66 | + const width = 3; |
| 67 | + const height = 3; |
| 68 | + const map = new FastMap<string>(width, height); |
| 69 | + |
| 70 | + map.Set(0, 0, 'a'); |
| 71 | + map.Set(2, 2, 'z'); |
| 72 | + |
| 73 | + // Avoid using `for..of` (requires downlevelIteration for es5 target). |
| 74 | + const fromDefault = Array.from((map as any)[Symbol.iterator]() as Iterable<[[number, number], string | undefined]>); |
| 75 | + |
| 76 | + expect(fromDefault).toEqual(Array.from(map.entries())); |
| 77 | + }); |
| 78 | +}); |
0 commit comments