Skip to content

Instantly share code, notes, and snippets.

@jason-s13r
Last active December 18, 2015 10:39
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 jason-s13r/5770182 to your computer and use it in GitHub Desktop.
Save jason-s13r/5770182 to your computer and use it in GitHub Desktop.
Why do I even do these things.
// 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