Skip to content

Instantly share code, notes, and snippets.

@sduquej
Created April 29, 2015 21:48
Show Gist options
  • Save sduquej/0611d9fd104c62740e69 to your computer and use it in GitHub Desktop.
Save sduquej/0611d9fd104c62740e69 to your computer and use it in GitHub Desktop.
01complejo.js
// Assumption: '1' is not a number, but a String, so it shouldn't be added.
// [‘a’, 2, 4, [‘1’, 5, ‘b’, [2,3, [‘a’, 4, [1,’b’,[5,’a’]]]]]]
(function (exports) {
'use strict';
var sum;
var getValue = function(element){
var value = 0;
if(typeof element === "number"){
value = element;
} else if(Array.isArray(element)){
value = element.reduce(function(sum, item){
sum += getValue(item);
return sum;
}, 0);
} else {
value = 0;
}
return value;
}
exports.complejo = function (array){
sum = 0;
if (!Array.isArray(array)) { console.error('you must pass an array as parameter'); return -1; }
if (0 === array.length) { console.error('array is empty'); return -1; }
array.forEach(function(element){
sum += getValue(element);
});
return sum;
}
})(typeof window === 'undefined' ? module.exports : window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment