Skip to content

Instantly share code, notes, and snippets.

@Alino
Last active July 12, 2018 20:15
Show Gist options
  • Save Alino/7f61ad28b093a5a0d615679bad8ebb00 to your computer and use it in GitHub Desktop.
Save Alino/7f61ad28b093a5a0d615679bad8ebb00 to your computer and use it in GitHub Desktop.
a simple javascript code for a guessing quiz without user interface.
const people = [{
name: 'Homer',
role: 'parent',
gender: 'male',
hobby: 'drinking beer'
}, {
name: 'Marge',
role: 'parent',
gender: 'female',
hobby: 'talking to sisters'
}, {
name: 'Bart',
role: 'child',
gender: 'male',
hobby: 'doing bad stuff'
}, {
name: 'Secret brother of Bart',
role: 'child',
gender: 'male',
hobby: 'hiding'
},
{
name: 'Lisa',
role: 'child',
gender: 'female',
hobby: 'reading books'
}, {
name: 'Maggie',
role: 'child',
gender: 'female'
}
];
const questions = [{
text: 'are you a male?',
filterKey: 'gender',
filterValue: 'male'
}, {
text: 'are you young?',
filterKey: 'role',
filterValue: 'child'
}, {
text: 'do you like doing bad stuff?',
filterKey: 'hobby',
filterValue: 'doing bad stuff'
}, {
text: 'do you like reading books?',
filterKey: 'hobby',
filterValue: 'reading books'
}, {
text: 'do you like talking to your sisters?',
filterKey: 'hobby',
filterValue: 'talking to sisters'
}, {
text: 'do you like drinking beer?',
filterKey: 'hobby',
filterValue: 'drinking beer'
}];
function askQuestions(questions) {
let result = people;
function ask(question) {
let answer = confirm(question.text);
if (answer) {
result = result.filter((person) => person[question.filterKey] == question.filterValue);
} else {
result = result.filter((person) => person[question.filterKey] !== question.filterValue);
}
if (result.length == 1) {
alert(`you are ${result[0].name}`);
return;
} else if (result.length == 0) {
alert(`there is no match for you.`);
return;
}
questions.shift();
questions = removeQuestionsRelatedToNobody(questions, result);
ask(questions[0]);
}
ask(questions[0]);
}
function removeQuestionsRelatedToNobody(questions, people) {
questions.map((q, i) => {
if (!_.find(people, q.filterKey) || !_.find(people, (p) => p[q.filterKey] === q.filterValue)) {
questions.splice(i, 1);
}
});
console.log('questions: ', questions);
console.log('people', people)
return questions;
}
askQuestions(questions);
@Alino
Copy link
Author

Alino commented Jul 12, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment