Lodash _.ternary() Method
Last Updated :
04 Dec, 2023
Lodash _.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 takes a single parameter as listed above and discussed 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 Lodash contrib library to be installed. The lodash-contrib library can be installed using npm install lodash-contrib –save
Example 1: In this example, the lodash-contrib library is used to create a ternary function (gfgFunc
) that takes another function (fun
) and returns its arguments.
Javascript
let _ = require( 'lodash-contrib' );
function fun() {
return arguments;
}
let gfgFunc = _.ternary(fun);
console.log( "Arguments are :" ,
gfgFunc( "first" , "second" , "third" ));
|
Output:
Arguments are : [Arguments]
{ '0': 'first', '1': 'second', '2': 'third' }
Example 2: In this example, the lodash-contrib library is used to create a ternary function (gfgFunc
) based on the fun
function.
Javascript
let _ = require( 'lodash-contrib' );
function fun() {
return arguments;
}
let gfgFunc = _.ternary(fun);
console.log( "Arguments are :" ,
gfgFunc( "a" , "b" , "c" , "d" , "e" , "f" ));
|
Output:
Arguments are : [Arguments] { '0': 'a', '1': 'b', '2': 'c' }
Example 3: In this example, we will add arguments but only the first 3 arguments will be using this method.
Javascript
let _ = require( 'lodash-contrib' );
function add() {
s = 0;
for (i = 0; i < 3; i++) {
s += arguments[i];
}
return s;
}
let gfgFunc = _.ternary(add);
console.log( "Sum of first 3 arguments is :" ,
gfgFunc(100, 100, 1000, 4, 5, 6, 7));
|
Output:
Sum of first 3 arguments is : 1200
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...