Gathering the output from every function within an array of functions

I've searched extensively for a solution to this dilemma, but have had no luck so far. Therefore, I am turning to the community for help. Please feel free to direct me to any existing similar queries.

My challenge involves working with an array of functions of unknown length (n). My goal is to execute all the methods and then aggregate the results of each function. While I'm aware that this can be achieved using both Array.prototype.map and Array.prototype.reduce, as shown below:

const arr = [
    () => 4,
    () => 5,
    () => 2,
];

const result = arr
    .map((f) => f())
    .reduce((acc, next) => acc + next);
// result = 11

This approach is already quite elegant, but I am curious if there exists an even more concise method utilizing just one array function. Ideally, I am looking for a native solution that could potentially incorporate custom types when used with TypeScript.

Answer №1

You have the ability to accomplish this using reduce method exclusively:

arr.reduce((accumulator, currentValue) => accumulator + currentValue(), 0)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Working with Typescript and JSX in React for event handling

I'm currently facing an issue with updating the state in a React component I'm developing using TypeScript (React with Addons 0.13.3, Typescript 1.6.0-dev.20150804, definition file from ). /// <reference path="react/react-addons.d.ts" /> i ...

Directive's ng-click function fails to execute

This directive contains a function that should be executed when clicked. ebApp.directive('monthDir', function () { return { restrict: 'E', templateUrl: 'htmlFiles/monthDirective.html', transclu ...

Instead of displaying the name, HTML reveals the ID

I have defined a status enum with different values such as Draft, Publish, OnHold, and Completed. export enum status { Draft = 1, Publish = 2, OnHold = 3, Completed = 4 } In my TypeScript file, I set the courseStatus variable to have a de ...

Angular fails to combine values within routerLink

The issue is straightforward - I have a component that retrieves the last searched items saved in sessionStorage as an array of ListItem objects: export class SearchlistComponent { results = JSON.parse(<string>sessionStorage.getItem("lastSear ...

What is the process for defining functions with distinct data types while allowing variables to have multiple data types?

I am facing a declaration issue - or rather, a challenge in comprehending Typescript. Let me illustrate the scenario: public migrationSource: Skater | Rink; public migrationDestination: Skater | Rink; public migrationMode: MigrationMode; ngOnInit() { ...

Recursive routing in NodeJS using Express

Certain website APIs have the capability to perform actions such as: Initial user's id their first friend, also a user v v GET /api/users/54282/friends/0/friends/0 ...

Why does JavaScript function flawlessly in FireFox, yet fails completely in other web browsers?

When it comes to browsing, FireFox is my go-to browser, especially for testing out my website Avoru. However, I recently encountered an issue when checking the functionality of my code on other major browsers like Google Chrome, Opera, and Safari. It seems ...

Having trouble with input functionality on iPad due to a CSS, LI, div, or clipping issue?

https://i.sstatic.net/muMSG.png One challenge I am facing is related to several inputs housed within an LI and div that are sortable using jQuery. The problem arises specifically on the iPad when attempting to click into the inputs to enter information - ...

Attempting to save MongoDB data into a variable for integration with Handlebars.js

Having an issue with storing MongoDB data in a variable to display in HTML using hbs. The specific error message is TypeError: Cannot read property 'collection' of undefined. Here's the code snippet I have written: const express = require(& ...

The application encountered an exception and has ceased to respond, displaying a custom error page

I have a .NET application running on IIS 7 that is accessed from IE7. When a specific exception occurs, the page is redirected to a plain .htm page with a back button that should take the user back to the previous page. This exception handling is implement ...

What is the best way to define a function agreement in Typescript?

I have created a function that can return `undefined` only when its argument is also `undefined`, otherwise it will always return a value derived from the argument provided. Here's an example of how the function works: function triple(value?: number) ...

What are some methods for controlling a webpage? Is it through HTML, JavaScript, Xpath, or

Hey there, I could really use your expertise on untangling a question that has me completely stumped. What exactly is the mechanism for controlling a webpage? a. HTML b. JavaScript c. Xpath d. CSS ...

SweetAlert html is not recognizing ng-app, but it functions correctly within the html body

When inserting a bootstrap table inside a SweetAlert, I encountered an issue where using ng-app or ng-repeat to populate data inside the table's rows did not call ng-app. However, when populating the table outside of the SweetAlert in the body, ng-app ...

Select dropdown in AngularJS for Date formatting

After retrieving json data from a web API, I found that it contains a series of datetimes. My goal is to select a specific datetime from a dropdown list. While I can populate the list without any issues, the formatting appears to be incorrect and I'm ...

There appears to be an issue with the v-model in the Vuetify v-btn-toggle

I have a situation where I am using two v-btn-toggles with multiple buttons in each. When selecting a button in the first toggle, it should impact which buttons are available in the second toggle based on a specific pattern: firstButtons: [ "a", "b", "c" ] ...

What is the best way to mandate the declaration or type of a function in TypeScript?

Let me present my dilemma: I am aiming to create a declaration file containing TypeScript function models. This file will be utilized by various individuals to build their own programs. To achieve this, I have crafted a def.d.ts file with a small example ...

Ensure the inferred type is asserted in TypeScript

Is there a more elegant approach to assert the type TypeScript inferred for a specific variable? Currently, I am using the following method: function assertType<T>(value: T) { /* no op */ } assertType<SomeType>(someValue); This technique prov ...

"Discover the step-by-step process of building a vue.js3 application with typescript, vue-router, and vuex without relying on

I have been assigned the task of developing a Vue3 application with TypeScript support using Vuex for state management and vue-router for basic routing. However, I am not allowed to use vue-cli for this project. Here is my current code: <head> & ...

Defining a custom type for accessing Date.getTime() in TypeScript

Are there any data types similar to Timestamp that could be utilized for Date().getTime() purposes? const currentTime = new Date().getTime(); ...

Searching for MongoDB / Mongoose - Using FindOneById with specific conditions to match the value of an array inside an object nestled within another array

Although the title of this question may be lengthy, I trust you grasp my meaning with an example. This represents my MongoDB structure: { "_id":{ "$oid":"62408e6bec1c0f7a413c093a" }, "visitors":[ { "firstSource":"12 ...