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
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")); |
Love that you took the effort to explain it, too :)
That explanation was mostly for me 😅
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.....