Skip to content

Instantly share code, notes, and snippets.

@dearfrankg
Last active August 19, 2018 11:10
Show Gist options
  • Save dearfrankg/e374a00cd861430926a3e4cafd214e09 to your computer and use it in GitHub Desktop.
Save dearfrankg/e374a00cd861430926a3e4cafd214e09 to your computer and use it in GitHub Desktop.
recursive practice
// helper functions
const format = data => JSON.stringify(data);
const title = title => console.log(`\n${title}\n---------------------`);
const iterate = (fnName, fn) => {
[1, 2, 3, 4, 5].forEach(n => {
console.log(`${fnName}(${n}) = ${fn(n)}`);
});
};
// WRITE FUNCTIONS IN A RECURSIVE WAY
// pow, fibonaci, factorial, map, reverse, sumSalaries
const pow = (b, n) => (n === 1 ? b : b * pow(b, n - 1));
const fibonaci = x => (x <= 1 ? 1 : fibonaci(x - 1) + fibonaci(x - 2));
const factorial = x => (x === 1 ? 1 : x * factorial(x - 1));
const map = (arr, fn) => (arr.length === 0 ? [] : fn(arr[0]).concat(map(arr.slice(1), fn)));
const reverse = s => (s.length === 1 ? s : s.slice(-1) + reverse(s.slice(0, -1)));
const sumSalaries = department => {
const isDepartment = Array.isArray(department);
if (isDepartment) {
return department.reduce((acc, person) => acc + person.salary, 0);
} else {
let sum = 0;
for (dept in department) {
sum += sumSalaries(department[dept]);
}
return sum;
}
};
// ==========================================================
// pow
title("pow");
const powOfBase2 = n => pow(2, n);
iterate("powOfBase2", powOfBase2);
// fibonaci
title("fibonaci");
iterate("fibonaci", fibonaci);
// factorial
title("factorial");
iterate("factorial", factorial);
// map
title("map");
const lettersArray = "abcde".split("");
const uppercase = x => x.toUpperCase();
console.log(`map(${format(lettersArray)}, uppercase) = ${map(lettersArray, uppercase)}`);
// reverse
title("reverse");
const word = "abcde";
console.log(`reverse(${format(word)}) = ${reverse(word)}`);
//sumSalaries
title("sumSalaries");
const company = {
sales: [{ name: "John", salary: 1000 }, { name: "Alice", salary: 600 }],
development: {
sites: [{ name: "Peter", salary: 2000 }, { name: "Alex", salary: 1800 }],
internals: [{ name: "Jack", salary: 1300 }]
}
};
console.log(`sumSalaries(company) = ${sumSalaries(company)}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment