I have a list like this: 125,248,11,486,3554,89,55
I need to have 2 textarea, in the first one i need to put the above list and after i click a button then in the second textarea i will get a list like this:
<!--startline-->[new text="table" ids="125,248,11"]
<!--startline-->[new text="table" files="2" ids="486,3554,89,55"]
So these are the rules:
- i need chunk size of 3 elements
- i need to add custom text before and after the chunk:
<!--startline-->[new text="table" ids="
+chunk
+"]
- if the last chunk has 2 or 1 element, then i need to merge it with
the previous one and the generated text for that chunk will be:
<!--startline-->[new text="table" files="2" ids="
+chunk
+"]
- every custom text and chunk will be on a new line, like in the above example
I found something that could help, using .slice
or .splice
but the problem is that i need to add custom text and not making an array like here: https://stackoverflow.com/a/47061736/1773862
So, any ideas? :)
----------- Solution:
const myList = document.getElementById('mylist');
const myNewList = document.getElementById('mynewlist');
const chunkSize = 3;
checkpoint = 0;
document.getElementById('generate').addEventListener('click', () => {
let chunks = myList.value.trim().split(',').reduce((all, one, i) => {
const ch = Math.floor(i / chunkSize);
all[ch] = [].concat((all[ch] || []), one);
checkpoint++;
return all
}, []);
let lastChunk = [...chunks[chunks.length-1]];
const lastone = chunks.length-2;
//alert(lastone);
if (lastChunk.length < chunkSize) {
chunks = chunks.slice(0, -1);
chunks[chunks.length - 1] = chunks[chunks.length - 1].concat(lastChunk);
checkpoint = 1;
}
myNewList.value = chunks.map((chunk,i) => `<!--startline-->[new text="table" ids="${chunk.join(',')}"]`).join('\n');
var content = myNewList.value;
var lastLine = content.substr(content.lastIndexOf("\n")+1);
var countnow = (lastLine.match(/,/g)||[]).length;
if (countnow > 2) {
var elem = document.getElementById('mynewlist');
var val = elem.value.split(/(\r\n|\n|\r)/g).filter(function(n){return n.trim()});
val.pop();
elem.value = val.join('\r\n');
lastLine = lastLine.replace("\"table\" ", "\"table\" \"files=\"2\" ");
elem.value += "\n" + lastLine;
}
});
<textarea id="mylist">30318,30319,30320,30321,30322,30323,30324,30325,30326,30327,30328,30329,30330,30331,30332,30333,30334,30335,30336,30337,30338,30339,30340,30341,30342,30343,30344,30345,30346,30347,30348,30349,30350,30351,30352,30353,30354,30355,30356,30357,30358,30359,30360,30361,30362,30363,30364,30365,123,999</textarea>
<br><br>
<button id="generate">Generate new list</button>
<br><br>
<textarea id="mynewlist" style="width: 538px; height: 294px;"></textarea>
Thanks to @mplungjan for the first part of the solution!