Skip to content

Instantly share code, notes, and snippets.

@philnash
Last active November 2, 2023 22:16
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 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"));
@dk5ax
Copy link

dk5ax commented Nov 1, 2023

Longer, but more readable than mine: https://gist.github.com/dk5ax/ca1d80b011a029f361cba3667682d9e8

You just might spend error handling around the JSON.parse.....however, sort of overkill in this context.....

@codepo8
Copy link

codepo8 commented Nov 2, 2023

Love that you took the effort to explain it, too :)

@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