JavaScript curry - invoking

Although I'm new to JavaScript, I find myself in a situation where I have to analyze someone else's code. I'm struggling to grasp the concept behind the following function and how to invoke it in node.

const invoke = method => object => object[method]

It appears that this function takes a method as a parameter and returns another function that in turn takes an object, ultimately returning object[method]. What exactly is the purpose of this function and how can it be utilized? Any insights are greatly appreciated. Thanks.

Answer №1

in my perspective, the const definition clearly indicates that it triggers a function stored in an object. As you mentioned, this can be simplified to:

const invoke = (method) => {    
    return (object) => {    
      return object[method] ;
    }
}

I believe the purpose of this is to make the code more readable and concise: to invoke the function a from the functions object ( functional-programming ).

Reading this article on functional programming

Functional programming is declarative rather than imperative, and application state flows through pure functions. Contrast with object oriented programming, where application state is usually shared and colocated with methods in objects.

However, the term invoke made me consider Immediately invoked functions. Therefore, the usage of const invoke can be:

Retrieve a function from the object (without executing it) to avoid instantiating the entire object, store the function in a variable, and potentially manipulate its prototype.

Call the function (with parentheses).

Access a property from an object.

Immediately invoke a function within an object.

const myFns = {
  'a' : function(x){
    console.log(x || 'something to log when no params passed');
  },
  'b': {
    username : 'Doe'
  } 
}

const invoke = method => object => object[method]

let myFunction = invoke('a')(myFns); 
myFunction('hello from myFunction'); // call it or modify myFunction.prototype ... etc.

invoke('a')(myFns)('hello'); // simply call it 

let user = invoke('b')(myFns); // get a property
console.log(user.username);

(invoke('a')(myFns))(); // immidiatly invoke the function

Possibly to avoid eval() :P

Answer №2

The term 'invoke' implies that it should be implemented in the following manner:

const invoke = method => object => object[method]()

The () represents the invocation. Since it is quite general, it's difficult to pinpoint exactly how it would be utilized, but here's a playful illustration.

class Cat {
    meow () { console.log('meow') }
}

var cats = [ new Cat(), new Cat(), new Cat() ];

cats.forEach( invoke( 'meow' ) );

-> 'meow'
-> 'meow'
-> 'meow'

It's a fairly common practice to have an array method like forEach execute the secondary function call of a higher-order function like this.

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

Troublesome Issue with ngAnimate and ngHide: Missing 'ng-hide-animate' Hook Class

I am working on a case where I need to add animation to a DOM object using the ngHide directive: Check out this example here Within this scenario, I have an array of JSON objects: $scope.items = [ {"key": 1, "values": []}, {"key": 2, "values": [ ...

Tips for testing views in ember.js using unit tests

We are currently delving into the world of Ember.js. Our development process is completely test-driven, and we aim to apply the same methodology to Ember.js. Having prior experience in test-driven development with Backbone.js apps using Jasmine or Mocha/Ch ...

Updating the value of a MongoDB item two days after its creation

I've been working on a NodeJS application that stores form data in a MongoDB database collection. My goal is to implement a function that can modify certain values of the object in the database collection 48 hours after the form data is initially save ...

Issues with Braintree webhooks and CSRF protection causing malfunction

I have successfully set up recurring payments with Braintree and everything is functioning properly. Below is an example of my code: app.post("/create_customer", function (req, res) { var customerRequest = { firstName: req.body.first_name, lastN ...

What is the best way to extract information from a dynamically generated input field using vanilla JavaScript?

Creating a dynamic input field inside the 'education-field' div is the main goal here. The user can add more fields by clicking the "Add more" button, and the data from these input fields is crucial for form validation purposes. Users can input t ...

What is the best method for creating thumbnail URLs for video files in HTML with JavaScript?

I am facing an issue with generating a thumburl for uploaded video files. After dynamically creating an input file and uploading local video files, I am able to retrieve the name and size of the file along with other information as shown in the screenshot ...

There was a problem with the WebSocket handshake: the response header value for 'Sec-WebSocket-Protocol' did not match any of the values sent

I've encountered an issue with my React project that involves streaming live video through a WebSocket. Whenever the camera firmware is updated, I face an error in establishing the WebSocket connection. Here's how I initiate the WebSocket: wsRe ...

Updating the parameters when clicking on each pagination button: A guide

Does anyone have advice on implementing pagination? I am currently working on loading a datatable with a few records initially. Once the page is loaded, I want to be able to click on pagination buttons like next or any pagination buttons to display a new s ...

Is it possible to dynamically change the color of a box shadow using an event handler?

I'm currently in the process of developing an application that consists of six distinct topics organized within a flexbox structure, complete with a box-shadow effect. My objective is to dynamically alter the color of the box-shadow through an event ...

Tips for confirming a sub string is present in an array using JavaScript/TScript

I am currently testing for the presence of a SubString within an array. In my test, I am asserting using: expect(classList).toContain('Rail__focused') However, I encountered the following error: Error: expect(received).toContain(expected // inde ...

Are there any factors within a local network or desktop environment that may impact the execution of JScript?

Something strange is happening with the JavaScript on my project. It works perfectly fine, except when accessed from computers at a specific company. Even more puzzling is that the JavaScript only fails about half of the time when accessed from that compan ...

Regular expression patterns for authenticating and verifying passwords

Currently, I am working on a JavaScript program to validate passwords using regex. Here are the requirements: The password must consist of at least seven characters. It should include at least one of the following: an uppercase letter (A-Z) a lowercas ...

JavaScript: Retrieving the following element from the parent container

Is there a way to prevent the next element within the parent tag from being enabled or disabled based on a certain condition? HTML: <span> <input type="checkbox" onchange="toggleInput(this)"> </span> <input type="text" ...

Is it possible to retrieve a JSON property using a string?

Here is the JSON I am working with: json_filter = {"CO": "blah"} I am attempting to access the member 'CO' using a string value, but the result keeps coming back as undefined. var selectedState = $(this).val(); // The state selected is 'C ...

How can I change the background color of a parent div when hovering over a child element using JavaScript

I am working on a task that involves three colored boxes within a div, each with a different color. The goal is to change the background-color of the parent div to match the color of the box being hovered over. CSS: .t1_colors { float: left; wid ...

Is the bearer terminology used for the authentication token or is it meant for a separate token?

In my MEVN application, I am incorporating JWT tokens and currently exploring how to transmit authentication tokens via axios. It is common practice to add "Bearer " before the token and have the server strip off "Bearer " to access the token's conten ...

When transmitting information to the server, the browser initiates four requests

I am encountering an issue with my React component. The problem arises when I try to retrieve the current geographic coordinates, as they are being fetched 4 times consecutively. This same glitch occurs when attempting to send the coordinates to the serv ...

Tips for modifying the input variables of the createControls function in JavaScript

I encountered an issue while working with a function createControls(){ return new THREE.TrackballControls( camera,domElement );} that was created using THREE.TrackballControls=function(object, domElement){.....} controls = createControls(camera, rende ...

Take command of the asynchronous loop

I have two Node.js applications that serve different purposes. The first is an Express.js Server (PROGRAM1), responsible for providing the user interface and RESTful APIs. The second is a web crawler (PROGRAM2), tasked with continuously reading items, do ...

Can the value in a JavaScript object be updated dynamically when a button is clicked?

In my JavaScript code, there is an object named annualPlan. Whenever a user submits the HTML form for a specific month, I aim to update the value in the object for that particular month accordingly. For instance, if someone submits August 21 and 200, I w ...