Template:Groningen/splitter js

var Splitter = {};

(function(){ var split = function(dna, size){ var total = Math.ceil(dna.length / size), dnaNum = DNA.padUInt(DNA.encodeUInt(total), 4); if(total > 255){ throw new Error("Cannot split into more than 255 chunks ("+total+")"); return; }

var ret = [], i; for(i = 0; i < total; i++){ ret.push(DNA.padUInt(DNA.encodeUInt(i), 4) + dnaNum + dna.substr(i * size, size)); }

return ret; };

var combine = function(state, dna){ var i = DNA.decodeUInt(dna.substr(0, 4)), total = DNA.decodeUInt(dna.substr(4, 4));

if(!state){ state = {'total': total, 'filled': 0, 'chunks': []}; }

if(state.total !== total){ throw new Error("Total number of chunks different: "+total+" / "+state.total); return; }

if(state.chunks[i] === undefined){ state.filled++; state.chunks[i] = dna.substr(8); }

if(state.filled === state.total){ return state.chunks.join(); }

return state; };

Splitter = { 'split': split, 'combine': combine }; })();