Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save peterwegren/472f09fdb684dde8af574af47a489df4 to your computer and use it in GitHub Desktop.
Save peterwegren/472f09fdb684dde8af574af47a489df4 to your computer and use it in GitHub Desktop.
How to call a JS function dynamically, and also pass in a variable number of dynamic arguments.
// INPUT:
// const largeSphere = {
// type: 'sphere',
// radius: 40
// }
// const smallSphere = {
// type: 'sphere',
// radius: 10
// }
// const cone = {
// type: 'cone',
// radius: 3,
// height: 5
// }
// const duck = [
// largeSphere,
// smallSphere,
// cone
// ]
const sphereVolume = function (radius) {
return (4/3) * Math.PI * Math.pow(radius, 3);
}
const coneVolume = function (radius, height) {
return (Math.PI * Math.pow(radius, 2) * height) / 3;
}
const prismVolume = function (height, width, depth) {
return (width * depth) * height;
}
// https://stackoverflow.com/questions/969743/how-do-i-call-a-dynamically-named-method-in-javascript
// https://stackoverflow.com/questions/2856059/passing-an-array-as-a-function-parameter-in-javascript/2856069#2856069
const totalVolume = function (solids) {
return solids.reduce((acc, curr) => {
return acc + volume[curr.type + 'Volume'](...Object.keys(curr).reduce((params, key) => {
if (key !== 'type') {
params.push(curr[key]);
}
return params;
}, []));
}, 0);
}
const volume = {
sphereVolume: sphereVolume,
coneVolume: coneVolume,
prismVolume: prismVolume
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment