Nothing beats a recursive solution when it comes to elegance IMO.
const chunk = (xs, n) => { if (xs.length <= n) return [xs]; return [ xs.slice(0, n), ...chunk(xs.slice(n), n) ]; };
If you're already in the mood for elegance, why not use a single expression arrow function?
const chunk = (xs, n) => (xs.length <= n) ? [xs] : [ xs.slice(0, n), ...chunk(xs.slice(n), n) ];
because IMO that's not more elegant.
I think guard clauses should live in the if statement that has nothing to do with the rest of the code. I think it is easier to read.
if
But I believe there is no absolute "elegance". Programming is just like art, different people perceive a piece differently.
Mm, Jason's version looks more readable to me. It's laid out a little more like you would if you were matching patterns in Haskell or something.
Here are my 2 cents. It is performant and avoids recursion.
const chunk = (xs, n) => xs.reduce((o, x, i) => { o[Math.floor(i/n)].push(x); return o; }, Array(Math.ceil(xs.length/n)).fill([]))
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nothing beats a recursive solution when it comes to elegance IMO.
If you're already in the mood for elegance, why not use a single expression arrow function?
because IMO that's not more elegant.
I think guard clauses should live in the
ifstatement that has nothing to do with the rest of the code. I think it is easier to read.But I believe there is no absolute "elegance". Programming is just like art, different people perceive a piece differently.
Mm, Jason's version looks more readable to me. It's laid out a little more like you would if you were matching patterns in Haskell or something.
Here are my 2 cents. It is performant and avoids recursion.