3
\$\begingroup\$

I created a simple quiz in HTML/CSS and plain Javascript. There are three questions with two options each, so there are eight possible combinations of answers, and therefore results. You can only pick one option per question.

This is how I am currently assigning a result to each combination in Javascript. The input is done through HTML.

function GetResult(){
var result;
var inputs = document.getElementsByTagName('input');
for(var i = 0, i < inputs.length, i++){
if(inputs[i].checked){
result = result + inputs[i].value;
}}

if(result == 'NaturalHistoricalRelaxed'){
//result A
}
if(result == 'NaturalHistoricalFast'){
//result B
}
if(result == 'NaturalModernRelaxed'){
//result C
}
if(result == 'NaturalModernFast'){
//result D
}
if(result == 'UrbanHistoricalRelaxed'){
//result E
}
if(result == 'UrbanHistoricalFast'){
//result F
}
if(result == 'UrbanModernRelaxed'){
//result G
}
if(result == 'UrbanModernFast'){
//result H
}
}

My question is, is there a better way of assigning each result to each combination?

I know that many people would tell me to use a Javascript library, but I don't want to, so please do not write answers like that.

\$\endgroup\$

bumped to the homepage by Community 2 days ago

This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

1
\$\begingroup\$

I am not familiar enough with JavaScript to write out the code while I am travelling, but I can at least describe a simple algorithm to do so generally in a faster and slightly simpler way. I here assume that you have access to the raw results and don't need to re-interpret them from the collected string.

For each answer we assign a 0 or 1 to the result, and then join them together as a bit mask, by shifting each answer by the 0-indexed numbering of the question it is an answer to. You can then construct an array of all the possible results, and when you want to know which result a response corresponds to, you can just construct an integer from the above bit mask and use it as an index for the array's result you want. If you have unique results for every response, then this is about as good as you can do (remember you can put a function in the array and call it if you want to do the compilation lazily). If you can construct the results from some kind of pattern, then you can find the right indexes by filtering the indexes with and based bit masked (with not applied to the result if you want the ones which have 0's in those masks).

\$\endgroup\$
  • \$\begingroup\$ You are describing a 'nominal' value. I like solutions that use existing structs to store 'complex' data. Unfortunately, I am out of votes. \$\endgroup\$ – dfhwze Jul 17 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.