let data = [1, 2, [3, 4]];
function flatSum(nums) {
//console.log('arguments', arguments);
if (Array.isArray(nums)) {
//let results = nums.map(flatSum),
// sum = results.reduce(function (a,b) { return a+b; }, 0);
let sum = 0;
nums.forEach(function (num) {
sum += flatSum(num);
});
return sum;
}
return nums;
}
// utility to make nice looking argument lists.
function formatArguments(args) {
let params = JSON.stringify(Array.prototype.slice.call(args));
return params.substr(1, params.length-2);
}
function reqDebugDecorator(func) {
let info = {
level: 0
},
decorated = function decorated() {
let indent = '│ '.repeat(info.level),
params = formatArguments(arguments);
console.log(`${indent}├───${params}`);
info.level += 1;
let result = func.apply(this, arguments);
info.level -= 1;
console.log(`${indent}│ └ = ${result}`);
return result;
};
return decorated;
}
console.clear();
flatSum = reqDebugDecorator(flatSum);
console.log('\nflat sum:', flatSum(data));
/*
// this is the function we will decorate with different capabilities.
function isPrime(num) {
if (num === 2 || num === 3) {
return true;
}
if (num % 2 === 0) {
return false;
}
let max = Math.ceil(Math.sqrt(num));
for (let i = 3; i <= max; i += 2) {
if (num % i === 0) {
return false;
}
}
return true;
}
// utility to make nice looking argument lists.
function formatArguments(args) {
let params = JSON.stringify(Array.prototype.slice.call(args));
return params.substr(1, params.length-2);
}
// utility to dynamically rename a function.
function renameFunction(func, name) {
Object.defineProperty(func, 'name', { value: name });
return func;
}
// decorator to log function calls with...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.