Utilizing functions as parameters and implementing a flexible number of arguments

I have two different functions:

Function called 'first' which takes 1 argument
Another function called 'second' that takes 2 arguments

Next, there is a third function that accepts a function and a value as its parameters.

I am struggling to understand how to make the third function capable of determining whether it is receiving one argument or two depending on the function passed in as the second argument???

**In the following example, when 'third' is invoked, it should output 2 for both calls at the end of the code.

let val = 12;

let val2 = 14
let toC = 14;

// If val === 12, returns 2 (takes only 1 argument)
const first = num => num === 12 ?2 :0;

// If val === toC, returns 2 (takes 2 arguments)
const second = (num, check) => num === check ?2 :0;

// Third function accepting a function and value as arguments
const third = (func, num) => {
  let temp = func(num);
  return temp;
}

// this works as expected
console.log(third(first, val);

// this does not work correctly
console.log(third(second, (val2, toC));

Answer №1

Upon close inspection, it appears that the purpose of the third function is simply to call the function provided as an argument and return its value. A more efficient approach in this scenario would be to utilize the rest parameters.

let val = 12;

let val2 = 14
let toC = 14;

// checks if val === 12 | takes 1 argument
const first = num => num === 12 ? 2 :0;

// checks if val === toC | takes 2 arguments
const second = (num, check) => num === check ?2 :0;

const third = (func, ...args) => {
  let temp = func(...args);
  return temp;
}


console.log(third(first, val));

console.log(third(second, val2, toC));

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

When attempting to use JQuery autocomplete, the loading process continues indefinitely without successfully triggering the intended function

Currently, I am utilizing JQuery autocomplete to invoke a PHP function via AJAX. Below is the code snippet I am working with: $("#client").autocomplete("get_course_list.php", { width: 260, matchContains: true, selectFirst: false }); Upon execution, ...

Challenges with conditional statements in JavaScript

This is a simple code snippet for a ToDo-List application. The function InputCheck() is designed to validate if the input bar contains any value. If the input bar is empty, the function should not trigger the addTodo function. However, in its current stat ...

MUI Input component does not support the use of the oninput attribute

My MUI Input component is defined like this, but the oninput attribute doesn't seem to work in MUI: <Input variant="standard" size="small" type="number" inputProps={{ min: '0', o ...

Click on the link to go to another page according to the drop-down option selected

Here's a puzzling query that even Google fails to address. I've got two pages: page-1 and page-2. On page-2, there is a <ul> element and a toggle-button-box with the following code: <ul> <li><button class="button is-checked ...

Updating part of a page while also changing the navigation

Apologies in advance, as this is my first attempt at coding a website. I have a specific need where I want to update only one div on my web page when a link in the navigation bar is clicked. <body> <div id="wrapper"> <header id= ...

Creating a JSX.Element as a prop within a TypeScript interface

I need to create an interface for a component that will accept a JSX.Element as a prop. I have been using ReactNode for this purpose, but I am facing issues when trying to display the icon. How can I resolve this issue? export interface firstLevelMenuItem ...

Steps to modify the border width upon gaining focus

I am struggling to adjust the border width when my input box is focused. Currently, it has a 1px solid border which changes to a 2px different color solid border upon focus. However, this change in border width is causing the containing div to shift by 1px ...

Tips for creating a 360 x 235 degree FOV image using three.js

My camera captures round images with a 235-degree field of view, like this one: https://i.sstatic.net/qNfrX.jpg I am familiar with threejs and have successfully rendered 360x360 images as equirectangular projections. However, I want to use threejs to rend ...

Vue's Global mixins causing repetitive fires

In an effort to modify page titles, I have developed a mixin using document.title and global mixins. The contents of my mixin file (title.ts) are as follows: import { Vue, Component } from 'vue-property-decorator' function getTitle(vm: any): s ...

Compilation unsuccessful. The LineGraph.js module could not be located due to recursion in resolving

After successfully installing react-chartjs-2 and chart.js using the command npm install --save react-chartjs-2 chart.js, I encountered an error when attempting to use LinkGraph: Failed to compile. ./src/LineGraph.js Module not found: Recursion in resolvi ...

What is the best way to determine the value of a variable specific to my scenario?

Using the Angular framework, I am trying to determine if the data variable updates when a button is clicked. Here is an example: <button ng-click='change()'>{{data}}</button> I want to verify if the data changes or log the data var ...

An error notification received from the command "jspm install jquery"

As I follow the tutorial on the jspm.io site, everything goes smoothly until I reach step 3. When I try to execute jspm install jquery, an error message pops up. The error reads: warn Error on getOverride for jspm:github, retrying (2). ReferenceError: ui ...

Recursively converting trees in JS/ES6

Currently, I am attempting to convert a tree structure provided in the following format: {"Parent": { "Child1": ["toy1"], "Child2": { "Nephew": ["toy2", "toy3"] } } } into a standardized tree form ...

How to add 1 to the final element in a JavaScript

I'm currently working on a task that involves incrementing the last element in an array using pop() and push(). However, I'm facing an issue where the original values are being retained after I try to increment the popped array. The objective is ...

Utilizing a form on numerous occasions prior to its submission

As a newcomer to JavaScript, I am exploring the best approach for a specific task. The task involves a form with checkboxes representing different music styles and a selector for names of people. The goal is to allow users to select music styles for mult ...

Discover the pixel width of a Bootstrap grid row or container using JavaScript

How can I calculate the width of a Bootstrap grid row or container in pixels using JavaScript? I am working with Aurelia for my JavaScript project, but I'm open to solutions in standard JS (no jQuery, please). Looking at the Bootstrap documentation, ...

Define characteristics of object contained within an array

My task involves handling an array of image objects: var pics = ["pic1","pic2","pic3","pic4","pic5","pic6"] I'm trying to loop through the array and adjust the style.left value by subtracting 10 from the current value. Here is what I attempted: for ...

I am interested in utilizing angular 4 ng2-ui/map with places-auto-complete functionality that is restricted to a specific country

Check out my code snippet below: <input class="form-control" placeholder="Pickup Location" places-auto-complete (place_changed)="pickupChanged($event)" formControlName="pickup_location" [types]="['geocode']" /> I am trying to figure out ...

Likelihood of triggering a function based on percentage

Hey everyone, I'm looking to add some randomness to the buttons on my website. I have a Button that could activate function one, function two or function three. However, I want to make it so there is a 60% chance that function one gets called from the ...

Is there a way to remove <font> tags using Javascript designMode?

Currently, I am in the process of developing a WYSIWYG editor as a hobby project. My approach involves utilizing an iframe with design mode enabled and leveraging the execcommand feature in JavaScript to implement the editor functionalities. For instance, ...