Skip to content

Instantly share code, notes, and snippets.

@alexmgrant
Last active December 4, 2020 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexmgrant/cddf0d9783e3a676bef9091a0d058809 to your computer and use it in GitHub Desktop.
Save alexmgrant/cddf0d9783e3a676bef9091a0d058809 to your computer and use it in GitHub Desktop.
Roomba Grid
import React, { useState } from 'react';
import './RoombaGrid.css';
// 90 right | 180 down | 270 left | 0 up
enum Direction {
'up' = 0,
'right' = 90,
'down' = 180,
'left' = 270,
}
// direction iteration
// right + 1 | down + 10 | left - 1 | up - 10
// had to give this obj key a type of number
const iteratorMap: { [key: number]: number } = {
[Direction.right]: 1,
[Direction.down]: 10,
[Direction.left]: -1,
[Direction.up]: -10,
};
const nintyDegrees = 90;
const startingCell = 0;
const Roomba = ({ direction = nintyDegrees }: any) => (
<div style={{ transform: `rotate(${direction}deg)` }}>👆</div>
);
const roombaGrid = [...new Array(100)].map((_, index) => index);
const getDirection = (direction: number) => {
direction =
direction === Direction.left ? Direction.up : direction + nintyDegrees;
return direction;
};
const getIterator = (direction: number) => iteratorMap[direction];
const hasNumber = (match: number) => (intiger: number) =>
intiger
.toString()
.split('')
.some((number) => Number(number) === match);
const hasNine = hasNumber(9);
const hasZero = hasNumber(0);
const checkBounds = (
position: number,
prevPosition: number,
direction: number
) => {
const upperLowerBounds =
position < startingCell || position > roombaGrid.length - 1;
const rightSideBounds =
hasNine(prevPosition) && direction === Direction.right;
const leftSideBounds = hasZero(prevPosition) && direction === Direction.left;
return upperLowerBounds || rightSideBounds || leftSideBounds;
};
const RoombaGrid = () => {
const [roombaPosition, setRoombaPosition] = useState(startingCell);
const [roombaDirection, setRoombaDirection] = useState(nintyDegrees);
const handleMoveForward = (direction: number, position: number) => {
const iterator = getIterator(direction);
const newPosition = position + iterator;
const isOutOfBounds = checkBounds(newPosition, position, direction);
if (isOutOfBounds) {
handleTurnRight();
} else {
setRoombaPosition(newPosition);
}
};
const handleTurnRight = () => {
setRoombaDirection(getDirection(roombaDirection));
};
return (
<>
<button
onClick={() => handleMoveForward(roombaDirection, roombaPosition)}
>
Move Forward
</button>
<button onClick={() => handleTurnRight()}>Turn Right</button>
<ul className="RoombaGrid">
{roombaGrid.map((cell) => (
<li key={cell}>
{cell === roombaPosition ? (
<Roomba direction={roombaDirection} />
) : null}
{cell}
</li>
))}
</ul>
</>
);
};
export default RoombaGrid;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment