I was wondering how efficient my code is creating custom indexOf for strings in JavaScript using regex instead of looping with a for
statement the whole way in most solution I find and I believe this got \$O(1)\$ since no loop is needed.
The idea is to use regex that put either the key or any list of word that is not key; this way I know that the value will be either in arr[0]
or arr[1]
. I also check using regex earlier whether the key exist in the value or not; this way I created non-looping indexOf with regex. This way I just return 0
if the key is in arr[0]
or arr[0].length
if it not in arr[0]
.
function findindex(value,key){ let regex = RegExp( "((?!"+key+").)+|"+key , "ig" ); //regex for separating keys in the array let regex2 = RegExp(key,"ig"); // regex for checking if the key is exist in the value or not //first check before looping whether key is available in array or not if( !regex2.test(value) || value.length < key.length ){ return -1; } let arr = value.match(regex); //make an array //alternative with condition statement return ( arr[0] === key || regex2.test(arr[0]) ) ? 0 : arr[0].length; }