Last active
December 18, 2015 10:39
-
-
Save jason-s13r/5770182 to your computer and use it in GitHub Desktop.
Why do I even do these things.
This file contains hidden or 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
// Consider this a class for the Question object. | |
function Question(question) { | |
var self = this; | |
// Private variables: | |
var correct = null; | |
var answers = []; | |
// Public Methods: | |
self.getQuestion = function () { | |
// This is a 'Getter' method. | |
// It exposes the value of a (private) property of the object. | |
// The property value cannot be changed. | |
return question; | |
}; | |
self.getAnswers = function () { | |
// Because JavaScript passes by reference, if this Getter was set up as: | |
// return answers; | |
// Then it would be possible to overwrite the answers array. | |
// By concatenating answers onto an empty array we are actually passing | |
// a copy of the answers array. | |
return [].concat(answers); | |
}; | |
self.addAnswer = function (answer, isCorrect) { | |
// Add an answer to the answers array. | |
// If it exists in the array, set it as correct if it is also correct. | |
var index = answers.indexOf(answer); | |
if (index > -1) { | |
correct = isCorrect ? index : correct; | |
return; | |
} | |
answers.push(answer); | |
// Recursively call so that it can be set to correct. | |
self.addAnswer(answer, isCorrect); | |
}; | |
self.checkAnswer = function (answer, answerIndex) { | |
answerIndex = answerIndex || answers.indexOf(answer); | |
return answerIndex === correct; | |
}; | |
} | |
var question = new Question('What colours are on the flag of Switzerland?'); | |
question.addAnswer('Black, Red and Yellow'); | |
question.addAnswer('Red, White and Blue'); | |
question.addAnswer('Red and White', true); | |
question.addAnswer('Yellow and Green'); | |
console.log(question); | |
console.log(question.getQuestion()); | |
console.log(question.getAnswers()); | |
console.log(question.checkAnswer('Black, Red and Yellow')); | |
console.log(question.checkAnswer('Red and White')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment