0

I have a usercase where I get an array of functions from backend something like:

var arr = [A(){}, B(){}, C(){}];

Now I need a way to execute them such that each function in the array is passed as a parameter to another function in the array.

A(B(C()));
1
  • 6
    arr.reduceRight((p, c) => c(p), undefined); Commented Feb 17, 2020 at 16:57

2 Answers 2

1

I'm curious how you managed to get the functions from the back-end, but it doesn't matter for your question, so here goes your answer:

var arr = [A(){}, B(){}, C(){}];

var value = arr[arr.length - 1]();

for (var i = arr.length - 2; i >= 0; i--) {
 value = arr[i](value);
}

console.log(value);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Array.prototype.reduce to execute consecutive calls to a list of functions.

Update: As ASDFGerte suggests, you can use reduceRight instead of reduce to reverse the function execution flow.

const text = 'That will be 3.50';
const funcList = [extractNumber, parseNumeric, formatCurrency];

console.log('Parsed:', chainFunctions(funcList, text));
console.log('Parsed:', chainFunctionsReverse(funcList.reverse(), text));

function chainFunctions(funcList, startingValue) {
  return funcList.reduce((result, func) => func(result), startingValue);
}

function chainFunctionsReverse(funcList, startingValue) {
  return funcList.reduceRight((result, func) => func(result), startingValue);
}

function extractNumber(str) {
  return str.match(/\b(\d+(\.\d+)?\b)/)[1];
}

function parseNumeric(numStr) {
  return parseFloat(numStr);
}

function formatCurrency(num) {
  return `$${num.toFixed(2)}`;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.