Converting a stringArray into a collection of function pointers for a librarySystem: A step-by

Right now, I am in the process of creating a library system

In the code snippet below, there is a stringArray ['greet','name'] used as dependencies. The goal is to convert this stringArray into an array of functions and pass it into greetingToName() using apply(). Is there a method to achieve this conversion?

function greet(){
  return 'hi!';
}

function name(){
 return 'name';
}

function greetingToName (greet, name) {
 console.log( greet() + ' ' + name() );
}



var stringArray = ['greet','name'];

greetingToName.apply(null, stringArray); // currently not functioning correctly, because it is passing 'greet' and 'name' as strings rather than function pointers.

Answer №1

To achieve the desired outcome, you can create an Object containing the necessary functions and pass the strings accordingly. Then, access the functions within the object using their names.

const availableFunctions = {
  sayHello: () => {
    return 'Hello!';
  },
  introduce: () => {
    return 'My name is...';
  }
};

function greetingAndIntroduction(sayHello, introduce) {
  console.log(availableFunctions[sayHello]() + ' ' + availableFunctions[introduce]());
}

const functionNames = ['sayHello', 'introduce'];
greetingAndIntroduction.apply(null, functionNames);

Answer №2

To achieve the desired outcome, one can create function variables and assign them within an array.

An example implementation is provided below:

var greeting = function(){
 return 'Hello!';
}

var personName = function(){
 return 'John';
} 

function combineGreetingWithName (greet, name) {
  console.log( greet() + ' ' + name() );
 }



var functionArray = [greeting, personName];

For a working demonstration, refer to the following Fiddle: https://jsfiddle.net/dk_dragonknight/yhL188se/

Answer №3

After reviewing everyone's solutions, I found great inspiration that led me to come up with a unique solution while keeping the function context intact. What are your thoughts on this approach?

var possibleFunctions = {
    greet : function(){
        return 'hello! ';
    },
    name : function(){
        return 'Professor Brilliant!';
    }
}


function combineGreetings (greet, name) {
 console.log( greet() + ' ' + name() );
}


var functionsArray = ['greet','name'];

// Create an array of functions by referencing possibleFunctions based on functionsArray
var arrayOfFunctions = functionsArray.map(function(functionName){
      return possibleFunctions[functionName];
});

combineGreetings.apply(window, arrayOfFunctions);

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

A guide to verifying the components of a row within a two-dimensional array

Currently, I am working on developing a three-in-a-row game. While I have successfully implemented the basic functionality, I am facing challenges when it comes to determining the winner of the game. Specifically, I need to check whether all elements in a ...

jQuery in SVG elements

Is there a method to execute jQuery within an SVG environment instead of HTML? I am aware of the jQuery svg plugin, but that is not what I am aiming for. Currently, the jQuery engine contains code snippets like this: div = document.createElement("div"); ...

Creating a custom file using a predefined template in Node.js: Step-by-step guide

To streamline my app development process in React Native, I have a specific workflow for creating new components. For example, if I need to add a Button component: First, I create a new folder path: /src/components/Button Then, I create a file named Butt ...

Configuring babel-loader in webpack for optimal HMR functionality

Recently, I encountered an issue while trying to add Hot Module Replacement (HMR) to my project. Despite the console showing that HMR was enabled and detecting changes in files, the view was not re-rendering. The console would display: [HMR] Updated modul ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

Verify if the user is currently active

Is there a method to determine if the user is not active? I am currently utilizing raw PHP. I would like for the user to be automatically logged out once they close the window, indicating their inactivity. I attempted implementing window.addEventListener ...

Muddled understanding concerning the utilization of ng-options

I am struggling with ng-options, as I have created a dropdown from an array defined in my controller. Below is my HTML code: <div ng-app> <div ng-controller="testCtrl"> <select multiple="multiple" ng-model="first" ng-options="c.name fo ...

Perform an Ajax POST request to a PHP script

Currently, I am facing a dilemma regarding how to post data from 9 checkboxes to my php script. I came across the following code: $.ajax({ type: "POST", url: "check.php", data: data, success: success, dataType: dataType }); However, I am unsure ...

Multiple requests were made by Ajax

I am facing an issue with my ajax code where it is being called multiple times. Below is my php code: (While loop extracts results from a database. For brevity, I have included just the modal and dropdown menu sections.) $rezPet = mysqli_query($kon, "SEL ...

How can GraphQL facilitate JOIN requests instead of multiple sequential requests?

I am working with two GraphQL types: type Author { id: String! name: String! } type Book { id: String! author: Author! name: String! } In my database structure, I have set up a foreign key relationship within the books table: table authors (e ...

Implement an event listener in a PHP server-side file to capture the onClick event with the

I am completely new to working with Ajax. In my application, I am using ajax along with a server-side php page named Req.php to retrieve records from a database, generate a table based on those fetched records, and then display it. Now, I am looking to inc ...

Refresh information by clicking on the data input

Essentially, I have a jsp file with a form and a hidden div structured like this: <div style="visibility:hidden;" id="popup"> //several input </div> <form> //several input </form> Both the div and form tags contain the sa ...

What is the best way to link my PHP with MySQL in order to execute an AJAX query?

I am currently working on making this page sortable using a dropdown selection menu. At the moment, there are only two different car makes displayed and they are not sorting properly. My ultimate goal is to enable sorting by make, model, and year, but I ne ...

Is the Angular Karma test failing to update the class properties with the method?

I am struggling to comprehend why my test is not passing. Snapshot of the Class: export class Viewer implements OnChanges { // ... selectedTimePeriod: number; timePeriods = [20, 30, 40]; constructor( /* ... */) { this.selectLa ...

Adjust the width of the graphics on both sides of the text based on the length of the text content

Is there a way to center an H1 tag between two graphics using CSS or jquery/javascript? The width of the H1 text will vary depending on the page. The dot on the left should remain at the edge of the site, and the line should extend to meet the edge of the ...

What is the best way to cycle through data using ngFor or similar methods when dealing with objects that have arrays

My data structure consists of an array of objects that resembles the following format: [ { id: 1, settings: "[{object},{object}]", <-- stringifiedJSON stats: "[{object}, {object}]" <-- stringifiedJSON }, { id: 2, set ...

Looking for a way to determine in JavaScript whether the last item in an array is a number or not? Keep in mind that the last element could be either a number or a string, depending

console.log("case 1") var event = "Year 2021"; console.log(typeof(parseInt(event.split(" ").pop())) === "number"); console.log("case 2") var event = "Year mukesh"; console.log(typeof(parseInt(event.split(" ").pop())) === "number"); console.log("case 3") va ...

JavaScript error: "null or not an object" bug

I have implemented the JavaScript code below to display horizontal scrolling text on the banner of my website. Surprisingly, it works perfectly fine on one server but throws an error on another server with the message: Error: 'this.mqo' is nul ...

Error encountered while attempting to convert CSV file: InvalidStateError

I've implemented a JavaScript function to be triggered by the 'onclick' event of an HTML button: function exportReportData2() { if ($("#Report").val() != "") { var screenParametersList = buildScreenParameters(); var ...

Experimenting with an Angular Controller that invokes a service and receives a promise as a

I am currently in the process of testing an angular controller that relies on a service with a method that returns a promise. I have created a jasmine spy object to simulate the service and its promise-returning method. However, my mock promise is not retu ...