Difference between revisions of "Template:Groningen/dna js"

 
Line 11: Line 11:
 
 
 
while(num){ // != 0
 
while(num){ // != 0
ret += bases[num & 3]; // lowest 2 bits as index to the base-pairs
+
ret += bases[num % 4]; // lowest 2 bits as index to the base-pairs
num = num >>> 2; // shift in next 2 bits
+
num = Math.floor(num / 4); // shift in next 2 bits
 
}
 
}
 
 

Latest revision as of 11:51, 26 August 2016

var DNA = {};

(function(){ var bases = 'ACTG';

var encodeUInt = function(num, len){ num = Math.floor(num); // truncate to int num = num < 0 ? -num : num; // make positive

var ret = num ?  : 'A'; // 0 -> A

while(num){ // != 0 ret += bases[num % 4]; // lowest 2 bits as index to the base-pairs num = Math.floor(num / 4); // shift in next 2 bits }

while(ret.length < len){ ret += 'A'; }

return ret; };

var decodeUInt = function(dna){ var ret = 0;

for(var i = 0; i < dna.length; i++){ ret *= 4; // shift first (does nothing first time)

var idx = bases.indexOf(dna[dna.length - i - 1]); if(idx === -1){ // not a base-pair return null; }

ret += idx; }

return ret; };

DNA = { 'encodeUInt': encodeUInt, 'decodeUInt': decodeUInt }; })();