Unveiling Parameters from a Function Transferred as an Argument to Another Function in JavaScript

I'm just getting started with JavaScript and I've encountered a small program where a function takes another function as an argument. My goal is to figure out how to extract or access the arguments of that passed in function. Here's a specific example:

function test(precondition, postcondition, func)   {
   // Need to extract the arguments of 'func', which should be 5 and 6 in this case
   // This extraction helps to verify if isNumber(5) and isNumber(6)
   // both return true, thus fulfilling the precondition
 }

var add = test((isNumber, isNumber), isNumber,
            function add(x, y) {return x+y; });

console.log(add (5, 6));

The function 'isNumber' returns true if the input is a number and it's already defined elsewhere. I've provided a minimal and runnable code snippet as per guidelines. Any assistance on this would be highly appreciated. Thank you!

Answer №1

One way to solve this is by making changes only in the test code (except for replacing (isNumber, isNumber) with [isNumber, isNumber] when calling test).

By creating the function inside test and returning it to be called via console.log(add(5, 6));, you can access add's arguments without any special treatment.

If you use arguments within a function, you will receive the arguments of that function as an array.

The ... in func(... arguments); represents the spread operator, which expands an array in place. For more information, check out spread operator.

function test(precondition, postcondition, func)   {
   // Extract arguments of func which should be 5 and 6
   // This is necessary to verify if isNumber(5) and isNumber(6)
   // both return true to meet the precondition  
  return function() {
    for (const i in arguments) {
      const argi = arguments[i];
      const precondition_i = precondition[i];
      console.log('precondition['+i+'] met: ' + precondition_i(argi));
    }
    const r = func(... arguments);
    console.log('postcondition met: ' + postcondition(r));
    return r;
  };
 }

var add = test([isNumber, isNumber], isNumber, function add(x, y) {return x+y; });

console.log(add(5, 6));

Alternatively, there's a more specific solution that avoids using arguments and ..., and doesn't pass an array as precondition:

function test(precondition, postcondition, func)   {
  // Extract arguments of func which should be 5 and 6
  // This is needed to confirm if isNumber(5) and isNumber(6)
  // both return true to satisfy the precondition  
  return function(x, y) {
    console.log('precondition met for x: ' + precondition(x));
    console.log('precondition met for y: ' + precondition(y));
    const r = func(x, y);
    console.log('postcondition met: ' + postcondition(r));
    return r;
  };
 }

var add = test(isNumber, isNumber, function add(x, y) {return x+y; });

console.log(add(5, 6));

Answer №2

function calculateSum(x, y){
    this.num1 = x;
    this.num2 = y;
    this.sumNumbers = function(){
        return this.num1 + this.num2;
    }
}
var my_calculation = new calculateSum(5, 6);
console.log(my_calculation.num1);   // returns 5
console.log(my_calculation.num2);  //returns 6
console.log(my_calculation.sumNumbers());  //returns 11

Answer №3

Attempt to invoke test from within add and provide only the parameters of add instead of the function call itself:

 function add(x,y){
     test(x,y)
     //followed by additional code
 }

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

Troubleshooting the Gutter Problem in jQuery Isotope and Masonry

Currently, I am utilizing the Isotope jQuery plugin. While it is a fantastic tool, I am encountering a minor issue with aligning items in masonry mode. The width of my container is 960px, and I aim to have 4 items perfectly aligned as if they were adhering ...

with every instance of an ajax request sent to a separate file

Currently, I have a forEach function that is printing the "local" column from a specific database: View image here Everything is working well up to this point, and this is the output I am getting: See result here Now, my goal is to send variables via P ...

GWT Validation - Enhance Your Application with a Third Party Library

Is there a reliable JavaScript library available for validating GWT fields such as Email, Text Length, Phone Number, Date & SSN, etc.? I am unable to use the GWT Validation Framework or GWT Errai in my application because I receive responses as JSON r ...

Checking the opacity with an if/else statement, then adding a class without removing the existing class

This function is designed to check the opacity of the header, which fades out as a user scrolls down. If the opacity is less than 1, it disables clickability by adding the class "headerclickoff". However, there seems to be an issue with removing the clas ...

AngularJS filter that retrieves only values that have an exact match

In my AngularJS application, I have a checkbox that acts as a filter: Here is the data being used: app.controller('listdata', function($scope, $http) { $scope.users = [{ "name": "pravin", "queue": [{ "number": "456", "st ...

In what ways can I incorporate Django template tags into my JavaScript code?

I've encountered an issue with implementing my model data into a FullCalendar library template in JavaScript. Despite seeing others do the same successfully, I keep getting errors as the template tags fail to register properly. <script> documen ...

Is there a way to automatically select all checkboxes when I select contacts in my case using Ionic 2?

initializeSelection() { for (var i = 0; i < this.groupedContacts.length; i++) { for(var j = 0; j < this.groupedContacts[i].length; j++) this.groupedContacts[i][j].selected = this.selectedAll; } } evaluateSelectionStatus() { ...

Obtain the option tag's name

One of my challenges is working with a dynamically created dropdown in HTML and having a dictionary in the back-end to retrieve keys. As users keep adding options to the dropdown, I face the issue of not having a value attribute like this: <option valu ...

Choosing a personalized component using document selector

Currently, I am working on an application using Stenciljs and have created a custom element like this: <custom-alert alertType="warning" alertId="warningMessage" hide>Be warned</custom-alert> The challenge arises when attem ...

What might be causing my Vue unit test to overlook a function?

I am in the process of creating unit tests for my component dateFormat.js using Jest. The focus is on testing the function formatDateGlobal. Here is an excerpt from the test: import DateFormat from '../dateFormat'; describe('dateFormat.js& ...

What steps do I need to take in order to ensure that when the word Hello is entered, the resulting output will display e:1, h:1, l:2, o:1

<!doctype HTML> <html> <body> <h3>Enter a string: </h3> <input id="myInput1" type="text"> <button onclick="count()">See output</button> //Click to see th ...

Issue with scroll down button functionality not functioning as expected

Is there a way to create a simple scroll down button that smoothly takes you to a specific section on the page? I've tried numerous buttons, jQuery, and JavaScript methods, but for some reason, it's not working as expected. The link is set up co ...

After performing an action with Redux, the error message ""Cannot access properties of 'undefined'" is displayed

I am currently developing a Shopping List App using React/Redux. I am facing issues with removing items from a list. When I trigger the 'removeItem' action, the page no longer recognizes the object that represents the list (which was originally s ...

What is the reason why certain variables in req.body can be read by Express.js while others cannot?

Currently, I am not utilizing body-parser and it is clear that I need to incorporate it. My query pertains to the inconsistency in how my variables are being accessed through req.body without body-parser. Some of the variables display undefined values whil ...

Learning the ropes: Building a model with nodejs using tensorflow.js

I am interested in creating an image classifier, but I lack knowledge of python. Since I am familiar with javascript, I have been considering using Tensorflow.js. Can models be trained with Tensorflow.js, and if so, what are the steps involved in the proce ...

Steps to resolve the error "Cannot POST /index.html" in Nginx, Express, and NodeJS

While setting up my MERN project on the production server, I encountered an issue. In order to manually type in URLs (like myproject.com/dashboard), I added the line try_files $uri /index.html; to the server section of my Nginx configuration file as recomm ...

Sticky box fails to maintain position as header scrolls

I am looking to create a Sidebar that sticks to the window while scrolling, but stops when it reaches the footer. I have managed to get it partially working, but there is a small issue that I can't seem to solve. Test it live here: Everything seems ...

In my specific scenario, what is the most effective method for retrieving data from an EntityFramework database using JavaScript?

Currently, within my ASP.NET MVC Core2 project, I have a model in the EF database that contains multiple properties: public class SchoolEvents { public long ID { get; set; } [Required] [StringLength(40, ErrorMessage = "Max 40 c ...

Invoking a PHP function within a JavaScript file

I'm facing an issue with calling a PHP function from JavaScript. I have written a code snippet where the PHP function should print the arguments it receives, but for some reason, I am not getting any output when running this code on Google Chrome. Can ...

Using a variety of objects in TypeScript arrays

How to effectively implement a superior class in TypeScript for an array containing diverse objects that inherit from the same class, without triggering errors? This is my attempt: interface IVehicle{ modelName: string } interface ICar extends IVehi ...