Skip to content

Instantly share code, notes, and snippets.

@abdus
Created June 17, 2018 15:07
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 abdus/1711193e88a32073169321756c70d243 to your computer and use it in GitHub Desktop.
Save abdus/1711193e88a32073169321756c70d243 to your computer and use it in GitHub Desktop.
// function for validating parameter
const validateParam = (param2validate) => {
if (!param2validate) return false;
if (param2validate.length === 0) return false;
if (typeof param2validate != 'string') return false;
};
const searchPhrase = (phrase, data) => {
if (validateParam(phrase) === false){
return console.error('Error Occured');
}
if (validateParam(data) === false){
return console.error('Error Occured');
}
let dataChunk = data.split('');
let firstCharInPhrase = phrase.split('')[0]; //to get the first Character of the phrase to be searched
let charPosInString = null; // to store the char which are matching and found in data
let arrCharIndex = []; // to store matching character position
for (let i=0; i<dataChunk.length; i++) {
if (firstCharInPhrase === dataChunk[i]) {
charPosInString = dataChunk[i];
arrCharIndex.push(i); // will be pushed to arrCharIndex for further ref
} else if (charPosInString === null && i === dataChunk.length - 1) return console.log(false);
}
// loop to get char pos and increase it's length number according to dataPhrase
let dataLengthCounter = []; // to store dataLength. Ex, for pos 8 and data.length 3; it will be dataLengthCounter[0] = [8, 9, 10]
for (let i=0; i<phrase.length; i++) {
dataLengthCounter[i] = []; // defining new array
}
// Loop to push arrCharIndex to dataLengthCounter
for(let i=0; i<phrase.length; i++) {
for (let j=0; j<phrase.length; j++) {
dataLengthCounter[i].push(arrCharIndex[i]);
arrCharIndex[i]++;
}
}
let word = [];
let wordArr = [];
for (let i=0; i<dataLengthCounter.length; i++) {
wordArr[i] = [];
}
for (let a in dataLengthCounter) {
for (let i=0; i<phrase.length; i++) {
for (let j in dataChunk) {
if (dataLengthCounter[a][i] === +j) {
wordArr[a].push(dataChunk[j]);
}
}
}
}
for (let i in wordArr) {
word[i] = wordArr[i].join('');
}
for (let i in word) {
if (phrase === word[i]) {
return console.log(true);
} else {
return console.log(false);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment