HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Codewars challenge - pair of shoes

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
shoescodewarspairchallenge

Problem

Yesterday you found some shoes in your room. Each shoe is described by two values:

  • type indicates if it's a left or a right shoe;



  • size is the size of the shoe.



Your task is to check whether it is possible to pair the shoes you found in such a way that each pair consists of a right and a left shoe of an equal size

For:

shoes = [[0, 21], 
       [1, 23], 
       [1, 21], 
       [0, 23]]


the output should be true;

For:

shoes = [[0, 21], 
       [1, 23], 
       [1, 21], 
       [1, 23]]


the output should be false.

So I wrote the code below,added some comments



` shoes = [[0, 21],
[1, 23],
[1, 21],
[0, 23]];

function pairOfShoes(shoes) {
//replace 0 with -1 so I can reduce them to 0 later if they are a pair
for (var i = 0; i



Seems convoluted to me can this code be improved?

Solution

Convert your test values where you need them

Your initial for loop only sets each "right / left" value to -1 if it is 0. This can be done in the reduce function itself. Also, your conditional p[c[1]] != undefined is unnecessary, as undefined evaluates to false, and there is no concern here about other "falsy" values such as zero.

Use Javascript's array methods

-
.some() can eliminate unnecessary for loops with conditionals in Javascript.

-
.values() lets you concisely iterate through values of an object.

Combined with the arrow operator =>, these can result in concise code that reads a little more like a natural sentence.

Applying both of the above points to your code:

shoes = [[0, 21], 
         [1, 23], 
         [1, 21], 
         [0, 23]];

function pairOfShoes(shoes) {
    var p = shoes.reduce(function(p, c) {
        p[c[1]] = (p[c[1]] || 0) + (c[0]==1 ? 1 : -1);
        return p;
    }, {});
    if (Object.values(p).some(x => x != 0)) { return false }
    else { return true };
}        

console.log(pairOfShoes(shoes));


[Edit: It might also be clearer to replace your reduce function with a `for' loop.]

Code Snippets

shoes = [[0, 21], 
         [1, 23], 
         [1, 21], 
         [0, 23]];

function pairOfShoes(shoes) {
    var p = shoes.reduce(function(p, c) {
        p[c[1]] = (p[c[1]] || 0) + (c[0]==1 ? 1 : -1);
        return p;
    }, {});
    if (Object.values(p).some(x => x != 0)) { return false }
    else { return true };
}        

console.log(pairOfShoes(shoes));

Context

StackExchange Code Review Q#157912, answer score: 2

Revisions (0)

No revisions yet.