Last active
April 20, 2016 21:39
-
-
Save liammclennan/771c195f501aa114e9f33d7804afa093 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// selectGame is a function that builds the data model for a game, by randomly selecting a set of books and a correct answer. | |
var selectGame = function () { | |
// `this` within selectGame is the array `data`. `reduce` is used to flatten the set of books into a single array. | |
// `_.shuffle` randomizes the list of books. | |
// `slice` selects the first 4 books. | |
// `books` is then 4 randomly selected books. | |
var books = _.shuffle(this.reduce(function (p, c, i) { | |
return p.concat(c.books); | |
}, [])).slice(0,4); | |
// `answer` is the one book (from books) randomly selected to be the answer | |
var answer = books[_.random(books.length-1)]; | |
return { | |
books: books, | |
// `author` is the author of the book selected to be the answer. This has to be looked up in `data`. | |
author: _.find(this, function (author) { | |
return author.books.some(function (title) { | |
return title === answer; | |
}); | |
}), | |
// `checkAnswer` is a function used within the game to check if the user's selection is the correct answer. | |
checkAnswer: function (title) { | |
return this.author.books.some(function (t) { | |
return t === title; | |
}); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment