From 4ed75021ca30e8fb592744ee85bfb91dbc4f0e5a Mon Sep 17 00:00:00 2001 From: Adam Laycock Date: Mon, 6 Dec 2021 15:35:55 +0000 Subject: [PATCH] feat: update createMap so that setRange can take a function --- src/functions/create-map.spec.ts | 14 ++++++++++++++ src/functions/create-map.ts | 14 +++++++++----- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/functions/create-map.spec.ts b/src/functions/create-map.spec.ts index 15259e1..e173cd1 100644 --- a/src/functions/create-map.spec.ts +++ b/src/functions/create-map.spec.ts @@ -19,5 +19,19 @@ describe('Create Map', () => { t2.setRange(2, 4, 2, 4, true) expect(t2.get(3, 4)).toBe(true) + + const t3 = createMap(9, 9, 0) + + t3.setRange(0, 2, 1, 1, v => { + return v + 1 + }) + + t3.setRange(1, 1, 0, 2, v => { + return v + 1 + }) + + expect(t3.get(0, 0)).toBe(0) + expect(t3.get(1, 1)).toBe(2) + expect(t3.get(0, 1)).toBe(1) }) }) diff --git a/src/functions/create-map.ts b/src/functions/create-map.ts index 6cdcbca..d1d7782 100644 --- a/src/functions/create-map.ts +++ b/src/functions/create-map.ts @@ -3,13 +3,13 @@ export interface Map { get(x: number, y: number): T /** Set the value of X,Y to `value` */ set(x: number, y: number, value: T): void - /** Set all the cells in the range to `value` */ + /** Set all the cells in the range to `value` or pass a function that takes the current value as its only argument and returns a new value. */ setRange( minX: number, maxX: number, minY: number, maxY: number, - value: T + value: T | ((current: T) => T) ): void /** The underlying map. Be warned this map maybe shifted so that 0 = minX etc... */ map: T[][] @@ -20,7 +20,7 @@ export interface Map { * * @param maxX The maximum X value. * @param maxY The maximum Y value. - * @param initialValue THe default value for all cells. + * @param initialValue The default value for all cells. * @param minX (Optional) The minimum X value, defaults to 0 * @param minY (Optional) The minimum Y value, defaults to 0 */ @@ -61,11 +61,15 @@ export const createMap = ( highX: number, lowY: number, highY: number, - value: T + value: T | ((current: T) => T) ) => { for (let y = lowY; y <= highY; y++) { for (let x = lowX; x <= highX; x++) { - set(x, y, value) + if (typeof value === 'function') { + set(x, y, (value as (current: T) => T)(get(x, y))) + } else { + set(x, y, value) + } } } }