My latest browser game is done, I have deployed it to a temporary website and will share the link to it soon. Anyway, while building it, I came across this little problem where I was trying to partition arrays. As usual, there’s more than one way to solve the problem. In fact, there are 3 ways to solve it. Let’s start with the least efficient solution.
Partition arrays
Inefficient i.e. n squared runtime. See we have to go (iterate) through all elements of the array twice.
Inefficient approach (using filter)
let correctAns = questionStack.filter(val => {
return val.userAns === val.correctAnswer;
});
let wrongAns = questionStack.filter(val => {
return val.userAns !== val.correctAnswer;
});
Old Fashioned (using old for loop)
Old fashioned but runs in linear time and I kinda like it.
let correctAns;
let wrongAns;
for(let i=0; i < questionStack.length; i++) {
let curQ = questionStack[i];
if(curQ.userAns == curQ.correctAnswer) {
correctAns.push(curQ);
} else {
wrongAns.push(curQ);
}
}
Modern (using reduce)
The one below is the by far the shortest and also the least readable in my opinion.
Array.prototype.partitionWith = function(f) {
return this.reduce((a, x) => a[f(x)+0].push(x) && a, [[],[]])
}
var isRight = x => x.userAns === x.correctAnswer;
var [right, wrong] = questionStack.partitionWith(isRight);
console.log(right);
console.log(wrong);
However it does run in linear time i.e. partitions the array in just one pass. The unreadability aspect is just my personal opinion a lot of Javascript developers would love this approach. To me, it’s less readable and harder to debug.
As usual, if you find any of my posts useful support us by buying or even trying one of our products and leave us a review on the app store.
[appbox appstore 1020072048]
[appbox appstore 1501784723]
[appbox appstore 1066820078]
[appbox appstore 1367294518]
[appbox appstore 1468791922]
[appbox googleplay com.mydaytodo.android.numbersgame]
[appbox appstore 1468826652]
[appbox appstore 1470834613]
[appbox googleplay com.mydaytodo.simplenotes]
[appbox appstore 1478331765]
0 Comments