Created
February 5, 2018 21:22
-
-
Save tejzpr/c53b05169718e7cea294dc75206470aa to your computer and use it in GitHub Desktop.
Javascript strstr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.strstr = function(needle) { | |
const haystack = this; | |
if(!needle) return [0]; | |
if(!haystack || needle.length > haystack.length) return [-1]; | |
let i,j; | |
let positions = []; | |
for(i=0;i<haystack.length;i++) { | |
let index = i; | |
j=0; | |
while(haystack[index] == needle[j]) { | |
if(j == needle.length-1) { | |
positions.push(i); | |
} | |
index++;j++; | |
} | |
} | |
return positions.length>0?positions:[-1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment