patternjavascriptModerate
Creating cards for a game of SET
Viewed 0 times
creatingcardsgameforset
Problem
I'm creating cards for a game of SET.
Can the following be rewritten in a more programmatic way, possibly getting rid of the embedded
Since this is code is targetting Node, I'm happy to use EcmaScript 6 features.
Can the following be rewritten in a more programmatic way, possibly getting rid of the embedded
for loops?function createCards() {
var cards = [];
var i, j, k, l;
for(i = 0; i < 3; i += 1)
for(j = 0; j < 3; j += 1)
for(k = 0; k < 3; k += 1)
for(l = 0; l < 3; l += 1)
cards.push([i, j, k, l]);
return cards;
}Since this is code is targetting Node, I'm happy to use EcmaScript 6 features.
Solution
I'm happy to use EcmaScript 6 features
Try array comprehensions!
Still, it translates to the same nested loops. If you need a variable nesting level, you can use a recursive solution.
Try array comprehensions!
var vals = range(0, 3);
return [ [i, j, k, l] for (i of vals) for (j of vals) for (k of vals) for (l of vals) ]Still, it translates to the same nested loops. If you need a variable nesting level, you can use a recursive solution.
Code Snippets
var vals = range(0, 3);
return [ [i, j, k, l] for (i of vals) for (j of vals) for (k of vals) for (l of vals) ]Context
StackExchange Code Review Q#20874, answer score: 13
Revisions (0)
No revisions yet.