Skip to content

Instantly share code, notes, and snippets.

@mathew-fleisch
Created June 9, 2021 20:19
Show Gist options
  • Save mathew-fleisch/d39e5210b4acbccebcb78ade1ffad4a9 to your computer and use it in GitHub Desktop.
Save mathew-fleisch/d39e5210b4acbccebcb78ade1ffad4a9 to your computer and use it in GitHub Desktop.
var input = [
["price", "display price of item"],
["owner", "show owner of item"],
["update", "sync cache with database"],
["delete", "delete item"],
["disassociate", "remove item from owner"]
]
// This function should display a menu of key/value pairs
// in a justified format, for viewing in a terminal/console
// Example Input:
// var input = [
// ["price", "display price of item"],
// ["owner", "show owner of item"],
// ["update", "sync cache with database"],
// ["delete", "delete item"],
// ["disassociate", "remove item from owner"]
// ]
// Example Output:
// ###########################################
// # price - display price of item #
// # owner - show owner of item #
// # update - sync cache with database #
// # delete - delete item #
// # disassociate - remove item from owner #
// ###########################################
function displayMenu(input) {
// First calculate the largest elements in each "column"
// The "key" (or first element of each array) will be displayed on the left column
let keyColumnMax = 0
// The "value" (or second element of each array) will be displayed on the right column
let valueColumnMax = 0
// The menu will also display an upper/lower boarder of the symbol "#"
let columnsMax = 0
// Identify the largest string length of each column
for (let i = 0; i < input.length; i++) {
if ( input[i][0].length > keyColumnMax ) {
keyColumnMax = input[i][0].length
}
if ( input[i][1].length > valueColumnMax ) {
valueColumnMax = input[i][1].length
}
}
// Calculate the boarder length (with extra padding for hardcoded characters)
columnsMax = valueColumnMax + keyColumnMax + 7
// Display upper boarder
console.log("#".repeat(columnsMax))
for (let i = 0; i < input.length; i++) {
let key = input[i][0]
let value = input[i][1]
let keySpace = " ".repeat(keyColumnMax-key.length)
let valueSpace = " ".repeat(valueColumnMax-value.length)
console.log("# " + keySpace + key + " - " + value + valueSpace + " #")
}
// Display lower boarder
console.log("#".repeat(columnsMax))
}
displayMenu(input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment