Skip to content

Instantly share code, notes, and snippets.

@gobwas
Last active December 22, 2015 00:19
Show Gist options
  • Save gobwas/6388292 to your computer and use it in GitHub Desktop.
Save gobwas/6388292 to your computer and use it in GitHub Desktop.
Combine strings algorithm.
/**
* 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