Created
August 19, 2018 09:29
-
-
Save dearfrankg/955b2d9a530a54378860c8d4f84d032b to your computer and use it in GitHub Desktop.
recursive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const util = require("util"); | |
// RECURSIVE FUNCTIONS: pow, fibonaci, factorial, map, reverse | |
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, dept) => acc + dept.salary, 0); | |
} else { | |
let sum = 0; | |
for (let dept in department) { | |
sum += sumSalaries(department[dept]); | |
console.log(`${dept}: ${sum}`); | |
} | |
return sum; | |
} | |
}; | |
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)}`)); | |
}; | |
title("power-of-base2"); | |
iterate("powOfBase2", x => pow(2, x)); | |
title("fibonaci"); | |
iterate("fib", fibonaci); | |
title("factorial"); | |
iterate("factorial", factorial); | |
// map | |
title("map"); | |
const upperCase = x => x.toUpperCase(); | |
const charArray = "abcde".split(""); | |
console.log(util.format("map(%j, upperCase) = %j", charArray, map(charArray, upperCase))); | |
// reverse | |
title("reverse"); | |
const string = "abcdef"; | |
console.log(`reverse(${string}) = ${reverse(string)}`); | |
// sumSalaries | |
title("sum salaries"); | |
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): "); | |
console.log(`total: ${sumSalaries(company)}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment