DEV Community

Cover image for JavaScript Katas: Split a number array into odd and even numbers

JavaScript Katas: Split a number array into odd and even numbers

miku86 on July 09, 2020

Intro 🌐 Today, I start a new series about code katas. I will take interesting katas of all levels and explain how to solve them. Probl...
Collapse
 
256hz profile image
Abe Dolinger


const splitNumbers = numbers => {
    const oddsAndEvens = { odds: [], evens: [] };

    numbers.forEach(number => {
        oddsAndEvens[number % 2 === 0 ? 'evens' : 'odds']
            .push(number);
    };

    return oddsAndEvens;
};

Collapse
 
miku86 profile image
miku86

Hi Abe,

nice solution, thanks!

Collapse
 
256hz profile image
Abe Dolinger

All credit to this post! codereview.stackexchange.com/a/162... Been using this at work and loving it.

Collapse
 
pentacular profile image
pentacular • Edited

The problem with katas is that they ignore the 'why' of the problem.

Since we don't know why we're doing this, let's delegate that problem to the caller as much as possible.

This is really a classification problem.

const splitNumber = (numbers, emitEven, emitOdd) =>
  numbers.forEach(n => (n % 2 ? emitOdd : emitEven)(number));

Now we can defer the arrangement of the classified numbers to someone else.

If they want to store them in arrays, then they can do that.

const even = [];
const odd = [];
splitNumber(numbers, n => even.push(n), n => odd.push(n));

But that's their problem.

Collapse
 
d4rthv4d3r profile image
Julián Chamalé

Nice analysis

Collapse
 
miku86 profile image
miku86

Hi,

thanks for your insights,
interesting question to think about!

Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

Or a simple reduce for the functional way

numbers.reduce((acc,val)=>{
return (val%2===1 ? {...acc,odd:[...acc.odd,val]}:{...acc,even:[...acc.even,val]});
},{odd:[],even:[]})

Collapse
 
monicamakes profile image
Monica

I was just going to comment, that this would also be done with reduce (my favorite)

Collapse
 
miku86 profile image
miku86

Hey there,

thanks for your solution!
Nice opportunity for people who want to step up their reduce-skills.

Collapse
 
sqlrob profile image
Robert Myers

Yeah, I would've gone with the reduce too, since that's only one iteration over the array, not two. Not sure I'd use spread though, wouldn't that kill the gain?

Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

Probably it would, so just mutate the acc and return it, I think even after all the solutions, I think the simple for loop performs the best.