The Underscore.js _.ternary() method returns a new function that accepts only three arguments and passes these arguments to the given function. Any additional arguments that are given are discarded.
Syntax:
_.ternary( fun )
Parameters: This method accepts a single parameter as mentioned above and described below:
- fun: This is the function that should be used for the parameters.
Return Value: This method returns a new function.
Note: This method will not work in normal JavaScript because it requires the underscore-contrib library to be installed. It can be installed using npm install underscore-contrib
Example 1:
Javascript
// Defining underscore contrib variable var _ = require('underscore-contrib');Â Â Â // Function to be used function fun() { Â Â Â Â return arguments; } Â Â // Making ternary function var gfgFunc = _.ternary(fun); Â Â console.log("Arguments are :", Â Â Â Â gfgFunc(1, 2, 3)); |
Output:
Arguments are : [Arguments] { '0': 1, '1': 2, '2': 3 }
Example 2:
Javascript
// Defining underscore contrib variable var _ = require('underscore-contrib');Â Â Â // Function to be used function fun() { Â Â Â Â return arguments; } Â Â // Making the ternary function var gfgFunc = _.ternary(fun); Â Â // Arguments more than 3 are excluded console.log("Arguments are :", Â Â Â Â gfgFunc(1, 2, 3, 4, 5, 6, 7, 8)); |
Output:Â
Arguments are : [Arguments] { '0': 1, '1': 2, '2': 3 }
Example 3: In this example, we will add arguments but only the first 3 arguments will be using this method.
Javascript
// Defining underscore contrib variable var _ = require('underscore-contrib');Â Â Â // Function to be used function add() { Â Â Â Â s=0; Â Â Â Â for (i=0; i<3; i++) { Â Â Â Â Â Â Â Â s+=arguments[i]; Â Â Â Â } Â Â Â Â return s; } Â Â // Making the ternary function var gfgFunc = _.ternary(add); Â Â // Arguments more than 3 are excluded console.log("Sum of first 3 arguments is :", Â Â Â Â gfgFunc(1, 2, 3, 4, 5, 6, 7)); |
Output:Â
Sum of first 3 arguments is : 6
