Skip to content

Instantly share code, notes, and snippets.

@wintercounter
Created September 15, 2014 21:22
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 wintercounter/d99f14451ef38da5fb0c to your computer and use it in GitHub Desktop.
Save wintercounter/d99f14451ef38da5fb0c to your computer and use it in GitHub Desktop.
Permutation class
var Permutation = function(str){
this.construct(str);
};
Permutation.prototype.originalString = undefined;
Permutation.prototype.results = new Object();
Permutation.prototype.mirrorResults = new Object();
Permutation.prototype.usedChars = new Array();
Permutation.prototype.construct = function(str){
this.originalString = str.toLowerCase();
};
Permutation.prototype.getPermutation = function(){
this._permutate(this.originalString);
this.results = Object.keys(this.results);
return this.results;
};
Permutation.prototype.getMirrors = function(){
this._findMirrors();
this.mirrorResults = Object.keys(this.mirrorResults);
return this.mirrorResults;
};
Permutation.prototype._permutate = function (str) {
var currentChar, allChars = str.split("");
for (var i = 0; i < allChars.length; i++) {
currentChar = allChars.splice(i, 1);
this.usedChars.push(currentChar);
if (allChars.length == 0) {
this.results[this.usedChars.join("")] = undefined;
}
this._permutate(allChars.join(""));
allChars.splice(i, 0, currentChar);
this.usedChars.pop();
}
};
Permutation.prototype._findMirrors = function(){
var stringLength = this.originalString.length,
halfLength = stringLength / 2;
if (stringLength % 2 === 1) {
return false;
}
if (!this.results) {
this.getPermutation();
}
this.results.forEach(function(value){
var firstHalf = '',
secondHalf = '';
for (var i = 0; i < halfLength; i ++) {
firstHalf += value[i];
secondHalf += value[((halfLength * 2 - 1) - i)];
}
if (firstHalf === secondHalf) {
this.mirrorResults[value] = undefined;
}
}.bind(this))
};
var Permutator = new Permutation('telet');
console.log('Permutations', Permutator.getPermutation());
console.log('Mirrors', Permutator.getMirrors());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment