Skip to content

Instantly share code, notes, and snippets.

@sammylupt
Created December 26, 2013 22:31
Show Gist options
  • Save sammylupt/8139578 to your computer and use it in GitHub Desktop.
Save sammylupt/8139578 to your computer and use it in GitHub Desktop.
/* JS Happy Number Finder
Run from command line with node happyNumberFinder.js [number]
*/
var _ = require('underscore');
var HappyNumberFinder = (function(_){
"use strict";
/* Private */
var results_array = [];
function splitNumberIntoPieces(number) {
var numberStringArray = number.toString().split('');
return _.map(numberStringArray, function(n) { return parseInt(n); });
}
function squareArrayAndSum(number_array) {
var squaredSums = _.chain(number_array)
.map(function(n) { return n * n; })
.inject(function(total_sum, eachNum) {
return total_sum += eachNum;
}, 0)
.value();
return squaredSums;
}
function checkIfNumberIsHappy(input) {
var numInPieces = splitNumberIntoPieces(input);
var squaredNumResult = squareArrayAndSum(numInPieces);
if (squaredNumResult == 1) {
console.log("--> This number is happy");
results_array = []; /* clear for repeated use of function */
} else {
returnOrContinue(squaredNumResult);
}
}
function returnOrContinue(number) {
console.log(number);
if (results_array.indexOf(number) != -1) {
console.log("This number is not happy");
return;
} else {
results_array.push(number);
checkIfNumberIsHappy(number);
}
}
/* Public */
function checkForNumber(input) {
checkIfNumberIsHappy(input)
}
return {
check: checkForNumber
}
}(_));
HappyNumberFinder.check(process.argv[2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment