Skip to content

Instantly share code, notes, and snippets.

@kraftdorian
Last active March 21, 2021 11:20
Show Gist options
  • Save kraftdorian/b41fc5559bc272a74d66c47c62ad9a78 to your computer and use it in GitHub Desktop.
Save kraftdorian/b41fc5559bc272a74d66c47c62ad9a78 to your computer and use it in GitHub Desktop.
Draw unicode square grid
const GRID_PARTS_VARIANT_LIGHT = 'LIGHT';
const GRID_PARTS_VARIANT_DOUBLE = 'DOUBLE';
const GRID_PART_VARIANTS_DICTIONARY = {
[GRID_PARTS_VARIANT_LIGHT]: '─│┌┐└┘├┤┬┴┼',
[GRID_PARTS_VARIANT_DOUBLE]: '═║╔╗╚╝╠╣╦╩╬'
};
/**
* Create grid parts mapping object
* @param gridPartsString
* @returns object
*/
const getGridPartsFromPartVariantsDictionaryString = (gridPartsString) => {
const [
HORIZONTAL,
VERTICAL,
DOWN_RIGHT,
DOWN_LEFT,
UP_RIGHT,
UP_LEFT,
VERTICAL_RIGHT,
VERTICAL_LEFT,
DOWN_HORIZONTAL,
UP_HORIZONTAL,
VERTICAL_HORIZONTAL,
] = gridPartsString.split('');
return {
HORIZONTAL,
VERTICAL,
DOWN_RIGHT,
DOWN_LEFT,
UP_RIGHT,
UP_LEFT,
VERTICAL_RIGHT,
VERTICAL_LEFT,
DOWN_HORIZONTAL,
UP_HORIZONTAL,
VERTICAL_HORIZONTAL
};
};
/**
* Draw the grid
* @param gp Grid parts
* @param dd Drawing depth
* @param cx Current X position
* @param cy Current Y position
* @param fd Final drawing string
* @returns string
*/
const drawGrid = (gp, dd, cx = 0, cy = 0, fd = '') => {
if (dd < 1 || cx > dd || cy > dd) {
return fd;
}
if (cx === 0 && cy === 0) {
cx++;
fd = fd + gp.DOWN_RIGHT + gp.HORIZONTAL;
} else if (cx === dd && cy === 0) {
cx = 0;
cy++;
fd = fd + gp.HORIZONTAL + gp.DOWN_LEFT + "\n";
} else if (cx === 0 && cy === dd) {
cx++;
fd = fd + gp.UP_RIGHT + gp.HORIZONTAL;
} else if (cx === dd && cy === dd) {
cx++;
cy++;
fd = fd + gp.HORIZONTAL + gp.UP_LEFT + "\n";
} else if (cx < dd && cy === 0) {
cx++;
fd = fd + gp.HORIZONTAL + gp.DOWN_HORIZONTAL + gp.HORIZONTAL;
} else if (cx < dd && cy === dd) {
cx++;
fd = fd + gp.HORIZONTAL + gp.UP_HORIZONTAL + gp.HORIZONTAL;
} else if (cx === 0 && cy < dd) {
cx++;
fd = fd + gp.VERTICAL_RIGHT + gp.HORIZONTAL;
} else if (cx === dd && cy < dd) {
cx = 0;
cy++;
fd = fd + gp.HORIZONTAL + gp.VERTICAL_LEFT + "\n";
} else if (cx < dd && cy < dd) {
cx++;
fd = fd + gp.HORIZONTAL + gp.VERTICAL_HORIZONTAL + gp.HORIZONTAL;
}
return drawGrid(gp, dd, cx, cy, fd);
};
@kraftdorian
Copy link
Author

kraftdorian commented Mar 21, 2021

Use case:

const unicodeGridDepth3Light = drawGrid(
  getGridPartsFromPartVariantsDictionaryString(GRID_PART_VARIANTS_DICTIONARY.LIGHT), 3
);
const unicodeGridDepth5Double = drawGrid(
  getGridPartsFromPartVariantsDictionaryString(GRID_PART_VARIANTS_DICTIONARY.DOUBLE), 5
);
console.log(unicodeGridDepth3Light);
console.log(unicodeGridDepth5Double);

Result:

┌──┬──┬──┐
├──┼──┼──┤
├──┼──┼──┤
└──┴──┴──┘

╔══╦══╦══╦══╦══╗
╠══╬══╬══╬══╬══╣
╠══╬══╬══╬══╬══╣
╠══╬══╬══╬══╬══╣
╠══╬══╬══╬══╬══╣
╚══╩══╩══╩══╩══╝

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment