Skip to content

Commit

Permalink
feat: update createMap so that setRange can take a function
Browse files Browse the repository at this point in the history
  • Loading branch information
Arcath committed Dec 6, 2021
1 parent 0878313 commit 4ed7502
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
14 changes: 14 additions & 0 deletions src/functions/create-map.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
14 changes: 9 additions & 5 deletions src/functions/create-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ export interface Map<T> {
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[][]
Expand All @@ -20,7 +20,7 @@ export interface Map<T> {
*
* @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
*/
Expand Down Expand Up @@ -61,11 +61,15 @@ export const createMap = <T>(
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)
}
}
}
}
Expand Down

0 comments on commit 4ed7502

Please sign in to comment.