Skip to content

Instantly share code, notes, and snippets.

@philnash
Last active November 2, 2023 22:16
Show Gist options
  • Save philnash/26dd64fc9896b982392818089e0619f4 to your computer and use it in GitHub Desktop.
Save philnash/26dd64fc9896b982392818089e0619f4 to your computer and use it in GitHub Desktop.
Puzzle: Event Block

Puzzle: Event Block

My JavaScript solution to the Code100 puzzle Event Block.

This will run in Node.js. Make sure the file is in the same directory as the JSON file. Then run

node event-block.mjs
import { readFileSync } from "fs";
import { fileURLToPath } from "url";
import { join, dirname } from "path";
function getData() {
const __dirname = dirname(fileURLToPath(import.meta.url));
const data = readFileSync(join(__dirname, "data.json"), "utf8");
return JSON.parse(data);
}
function blankLine(columns, padChar) {
return padChar.repeat(columns);
}
function eventLine(columns, padChar, event) {
let line = "";
const { name, date, location } = event;
line += `${padChar} ${name} `;
const endLine = ` ${date} ${padChar}`;
if (location) {
// Find the centre of the location string (add 2 to account for spaces).
const halfLocationLength = Math.floor((location.length + 2) / 2);
// Find the centre of the line
const halfWidth = Math.floor(columns / 2);
// Find the start of the location string within the columns.
const locationStart = halfWidth - halfLocationLength;
// Add enough padChars to get to one before the location string.
line += padChar.repeat(locationStart - line.length - 1);
line += ` ${location} `;
}
// The remaining padding is the difference between the columns and the current
// line length plus the last part of the line.
line += padChar.repeat(columns - line.length - endLine.length);
line += endLine;
return line;
}
function run() {
const data = getData();
const { columns, padChar, events } = data;
const result = [];
result.push(blankLine(columns, padChar));
events.forEach((event) => result.push(eventLine(columns, padChar, event)));
result.push(blankLine(columns, padChar));
return result;
}
const result = run();
console.log(result.join("\n"));
@philnash
Copy link
Author

philnash commented Nov 2, 2023

That explanation was mostly for me 😅

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