Last active
December 22, 2015 00:19
-
-
Save gobwas/6388292 to your computer and use it in GitHub Desktop.
Combine strings algorithm.
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
/** | |
* Combine algorithm. | |
* | |
* @author Sergey Kamardin <[email protected]> | |
* | |
* Usage: | |
* | |
* combine(['a','b']) | |
* | |
* Will return ['ab', 'ba']; | |
* | |
* Also possible to pass object agains Array, which can content params: atoms, combiner, regexp. | |
* - atoms is a symbols array (like ['a','b']); | |
* - combiner is a function, that will be called each time, when need to concat two symbols. | |
* If this function return string or array, it will be added to the final result, if another type, then not. | |
* - regexp is a sprintf style template (only with %s) that will be converted to check dobules in result set. | |
* | |
*/ | |
function combine(context) { | |
var atoms, molecules, level, | |
regexp = '%s', | |
combiner = function(one, two) { | |
return [one, two].join('') | |
}; | |
// Options initialization | |
if (Object.prototype.toString.call(context) == '[object Array]') { | |
atoms = context; | |
molecules = atoms.slice(); | |
level = atoms.length; | |
} else { | |
atoms = context.atoms; | |
molecules = context.molecules || context.atoms.slice(); | |
level = context.level || context.atoms.length; | |
combiner = context.combiner || combiner; | |
regexp = context.regexp || regexp; | |
} | |
// Need to calculate the deep of recursion for stop in the future. | |
level--; | |
var response = []; | |
if (level == 0) return response; | |
$.each(molecules, function(i, molecula) { | |
var iterationResult = []; | |
$.each(atoms, function(i, atom) { | |
var test = new RegExp(regexp.replace('%s', atom)); | |
if (!test.test(molecula)) { | |
var result = combiner.call(null, molecula, atom); | |
if (typeof result == 'string') iterationResult.push(result); | |
if (Object.prototype.toString.call(result) == '[object Array]') $.merge(iterationResult, result); | |
} | |
}); | |
$.merge(iterationResult, combine({atoms: atoms, molecules: iterationResult, level: level, combiner: combiner})); | |
$.merge(response, iterationResult); | |
}); | |
return response; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment