JSFiddle - React, Tailwind, and code Playground

by Alexandru Mihai

JavaScript

let str='CGTGACAGTGTATGGGCATCTTT';
let pattern='TGT';
let d=1;
const hamming = (str1,str2) => str1.split('').filter((a,i)=>str2[i]!=a).length;
function approx(text,pattern,d){
	count=0;
  for(i=0;i<text.length-pattern.length+1;i++){
  	patternPrime = text.substr(i,pattern.length);
    if(hamming(pattern,patternPrime)<=d)
    	count++
  }
  return count;
}
String.prototype.replaceAt=function(index, replacement) {
    return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}

function ImmediateNeighbors(pattern){
	neighborhood=[pattern];
  for(var i=1;i<pattern.length;i++){
  	symbol = pattern[i];
    let differentSymbol = ['A','C','G','T'].filter(a => a!=symbol);
    differentSymbol.forEach(function(n){
      let copyPattern = (' ' + pattern).slice(1);
    	copyPattern = copyPattern.replaceAt(i,n);	
      neighbor = copyPattern;
      neighborhood.push(neighbor);
    });
  }
  return neighborhood;
}

function func(pattern,d){
   Neighborhood=[pattern];
   for(j=1;j<=d;j++){
       for(i=0;i<Neighborhood.length;i++){
       	 Neighborhood.push(...ImmediateNeighbors(Neighborhood[i]));
         Neighborhood=[...new Set(Neighborhood)];
       }
   }
   return Neighborhood;
}

console.log(approx(str,pattern,d));
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~');
console.log(hamming('TGACCCGTTATGCTCGAGTTCGGTCAGAGCGTCATTGCGAGTAGTCGTTTGCTTTCTCAAACTCC','GAGCGATTAAGCGTGACAGCCCCAGGGAACCCACAAAACGTGATCGCAGTCCATCCGATCATACA'))
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~');
console.log(func('TGCAT',3))
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~');