Created
October 28, 2016 05:37
-
-
Save RameshRM/59c79e0bec07502b6b5b27811f74e153 to your computer and use it in GitHub Desktop.
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
'use strict'; | |
var input = 'cbabadcbbabbcbabaabccbabc'; | |
var match = 'abbc'; | |
var matches = []; | |
var weight = getWeight('abad'); | |
var result = []; | |
for (var i = 0; i < input.length; i++) { | |
if (getWeight(input.substr(i, match.length)) === weight) { | |
matches.push(i); | |
} | |
} | |
matches = matches.map(function forEach(idx) { | |
var slidingStr = input.substr(idx, match.length); | |
return hasMatch(slidingStr, match) ? slidingStr : undefined; | |
}).filter(function filter(item) { | |
return item !== undefined; | |
}); | |
console.log(matches); | |
function getWeight(input) { | |
input = input && input.toLowerCase() || ''; | |
var total = 0; | |
for (var i = 0; i < input.length; i++) { | |
var char = input.charCodeAt(i); | |
var hash = ((hash << 5) - hash) + char; | |
total += input.charCodeAt(i); | |
} | |
return total; | |
} | |
function hasMatch(input, target) { | |
for (var i = 0; i < input.length; i++) { | |
if (target.indexOf(input[i]) < 0) { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment