I just had to split up an array of items into chunks with alternating one and two elements.
Here are two versions, the first one is written by me, the second one was generated by GitHub Copilot.
My own version
What I like most is that this is the very first time I've had to define more than one variable in a for
statement!
It should also work for more complex scenarios.
const items = [0,0,0,0,0,0];
const rows = [];
for (let i = 0, countThisRow; i < items.length; i += countThisRow) {
// Change this according to your needs
if (rows.length % 2 === 0) {
countThisRow = 1;
} else {
countThisRow = 2;
}
rows.push(items.slice(i, i + countThisRow));
}
console.log(rows);
// Result:
// [
// [0],
// [0, 0],
// [0],
// [0, 0]
// ]
The AI version
While I was coding, Copilot failed to help me with this. Later I promted the chat and this is the version that was generated. Surprisingly it does not even work, I really thought that this is exactly something that Copilot is good for.
And even if I did correct it, it's a pain to read, isn't it?
If you find a prompt that works better let me know!
Prompt
I have to split up an array of many items into chunks with alternating one and two elements. Like from [0,0,0,0,0,0] to [0],[0,0],[0],[0,0]
Response
Sure! Here's an example function that takes an array and returns a new array with alternating chunks of one and two elements:
function alternateChunks(arr: any[]): any[] {
const result = [];
let i = 0;
while (i < arr.length) {
if (i === arr.length - 1) {
result.push([arr[i]]);
break;
}
result.push(arr.slice(i, i + 2));
i += 2;
if (i === arr.length - 1) {
result.push([arr[i]]);
break;
}
}
return result;
}
You can call this function with your array of items as an argument to get a new array with alternating chunks. For example, alternateChunks([0, 0, 0, 0, 0, 0]) would return [[0], [0, 0], [0], [0, 0]].
Your are lying Copilot 😜
I do not trust AI code.
However, AI can sometimes be helpful for simple brainstorming.
For example, after asking AI to implement a piece of code, I might see that the code uses
arr.slice
, and that might spark an idea for the correct implementation.Additionally, judging by the thumbnail image of the article, the initial value of
countThisRow
might need to be1
.Finally, here is my own implementation of the given problem.