Skip to content

Instantly share code, notes, and snippets.

@nacholibre
Created June 2, 2015 20:12
Show Gist options
  • Save nacholibre/475bdd94d757868dd63a to your computer and use it in GitHub Desktop.
Save nacholibre/475bdd94d757868dd63a to your computer and use it in GitHub Desktop.
palindromes
'use strict';
var assert = require('assert');
function reverseString(str) {
return str.split('').reverse().join('');
}
function getRotations(str) {
str = str.trim();
var rotations = [];
rotations.push(str);
for (var pos = 1; pos < str.length; pos++) {
var left = str.substr(0, pos);
var right = str.substr(pos);
var rotation = reverseString(left) + reverseString(right);
rotations.push(rotation);
}
return rotations;
}
function getPalindromes(str) {
return getRotations(str).filter(validPalindrome);
}
function validPalindrome(str) {
var valid = true;
if (!str) {
valid = false;
}
var splitted = str.split('');
while (splitted.length > 0 && valid === true) {
var left = splitted.shift();
var right = splitted.pop();
if (left && right && left !== right) {
valid = false;
break;
} else if(splitted.length === 2 && splitted[0] === splitted[1]) {
break;
}
}
return valid;
}
function testPalindromes() {
var palin;
palin = getPalindromes('asd');
assert (palin.length === 0);
palin = getPalindromes('alabala');
assert (palin.length === 1);
assert (palin[0] === 'alabala');
palin = getPalindromes('akawwaka');
assert (palin.length === 2);
assert (palin[0] === 'akawwaka');
assert (palin[1] === 'wakaakaw');
palin = getPalindromes('b');
assert (palin.length === 1);
assert (palin[0] === 'b');
palin = getPalindromes('abba');
assert (palin.length === 2);
assert (palin[0] === 'abba');
assert (palin[1] === 'baab');
palin = getPalindromes('kamak');
assert (palin.length === 1);
assert (palin[0] === 'kamak');
palin = getPalindromes('bird');
assert (palin.length === 0);
palin = getPalindromes('');
assert (palin.length === 0);
console.log('tests passed!');
}
//testPalindromes();
var stdinData = '';
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
stdinData = stdinData + chunk;
} else {
var palindromes = getPalindromes(stdinData);
if (palindromes.length) {
palindromes.forEach(function(palin) {
console.log(palin);
});
} else {
console.log('NONE');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment