Skip to content

Instantly share code, notes, and snippets.

@dvidsilva
Last active December 25, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvidsilva/6987761 to your computer and use it in GitHub Desktop.
Save dvidsilva/6987761 to your computer and use it in GitHub Desktop.
Find the places where certain pattern occur in a string using JS, keeping in mind interpolation and not repeating the result. Is using node :P
var start = new Date().getTime();
var str="";
var mtc="CTTGATCAT";
var n = " ";
var alr = new Array();
var j = 0;
var url = 'https://beta.stepic.org/media/attachments/lessons/3/Vibrio_cholerae.txt';
var http = require('https');
var fs = require('fs');
function storeOutput(txt){
fs.writeFile("output.txt", txt , function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
}
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
function findPatterns(str){
str = str.toString();
for(var i = 0; i < str.length; i++){
j = str.indexOf(mtc,i);
console.log(i);
if( j != -1 && !inArray(j,alr) ){
alr.push(j);
n += " " + j;
}
}
var total = j.length;
console.log( "the pattern was found this many times: " + total );
var end = new Date().getTime() - start;
console.log(" it took so many time in the operation " + end );
return n;
}
function httpGet(theUrl){
var req = http.get(theUrl,function(res){
res.on('data',function(chunk){
str += chunk;
});
res.on('end',function(){
output = findPatterns(str);
storeOutput(output);
});
});
req.write('data\n');
req.write('data\n');
req.end();
}
// httpGet(url);
// now i'm reading a file from disk instead of from a url that took forever
fs.readFile('str.txt', function(err,data){
console.log(1);
output = findPatterns(data);
console.log(2);
storeOutput(output);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment