Skip to content

Instantly share code, notes, and snippets.

@johanandren
Created April 10, 2013 12:51
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 johanandren/5354330 to your computer and use it in GitHub Desktop.
Save johanandren/5354330 to your computer and use it in GitHub Desktop.
Min måttligt ambitiösa adressbok för mejslas JavaScript-cirkel 2013
// redefine read so that it returns strings
read = (function() {
var oldRead = read
return function(prompt) {
return oldRead(prompt) + "";
}
})();
// show a menu based on a input list of menu items
// menuItems: [{ key: 'K', action: function, desc: 'Description' }, ...]
function showMenu(menuItems) {
var done = false
var menu = {
// quit the event loop
Q: { action: function() { done = true }, desc: "Quit" },
// print the entire menu
print: function() {
for (key in menu) {
if (key.length == 1 && menu.hasOwnProperty(key)) {
var item = menu[key]
println(key + ": " + item.desc)
}
}
},
handleInput: function() {
var input = read().toUpperCase()
var selected = menu[input]
if (selected && selected.action) {
selected.action()
} else {
println("Unknown menu option " + input)
}
}
}
// add each menu item to the menu
menuItems.forEach(function(item) {
menu[item.key] = item
})
// event loop
while (!done) {
menu.print()
menu.handleInput()
}
}
function createAddressBook() {
var db = []
return {
addAddress: function() {
println("Add address:")
db.push({
name: read("Name: "),
street: read("Street: "),
zip: read("Zip Code: "),
city: read("City: ")
})
},
listAddresses: function() {
if (db.length == 0) {
println("Addressbook is empty!")
} else {
println("All addresses:")
db.forEach(function(entry) {
println("Name: " + entry.name +
", Street: " + entry.street + " Zip Code: " + entry.zip +
", City: " + entry.city)
})
}
},
deleteAddress: function() {
println("Delete address:")
var index = read("Entry no to delete: ")
db.splice(index, 1)
}
}
}
var addressBook = createAddressBook();
showMenu([
{ key: "A", action: addressBook.addAddress, desc: "Add an address" },
{ key: "D", action: addressBook.deleteAddress, desc: "Delete an address" },
{ key: "P", action: addressBook.listAddresses, desc: "Print all addresses" }
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment