Syntax, Parameter and Return Value
Syntax:
_.cond(pairs)
Parameters:
pairs (Array): An array of condition-result pairs, each pair as an array with a predicate function and a corresponding function to execute.
Return Value:
(Function) - Returns a new function that will check the conditions in the provided pairs and execute the corresponding function for the first truthy condition.
Examples
Using _.cond() for Simple Conditional Logic:
JavaScript
var _ = require('lodash');
var classifyAge = _.cond([
[age => age < 18, () => 'Child'],
[age => age < 65, () => 'Adult'],
[() => true, () => 'Senior']
]);
console.log(classifyAge(25));
console.log(classifyAge(70));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'Adult'
'Senior'
Demonstrates classifying ages into categories based on conditions.
Complex Conditional Logic:
var handleEvent = _.cond([
[event => event.type === 'click', () => handleOnClick(event)],
[event => event.type === 'hover', () => handleOnHover(event)],
[() => true, () => handleDefault(event)]
]);
// Usage
handleEvent({ type: 'click' });
handleEvent({ type: 'unknown' });

You can also try this code with Online Javascript Compiler
Run Code
Shows handling different types of events with specific functions.
Using With Array Operations:
JavaScript
var processItems = _.cond([
[items => _.isEmpty(items), () => 'No items to process'],
[items => items.length > 5, () => 'Processing in batches'],
[() => true, items => `Processing ${items.length} items`]
]);
console.log(processItems([]));
console.log(processItems([1, 2, 3, 4, 5, 6]));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'No items to process'
'Processing in batches'
An example of processing arrays based on their length.
Error Handling:
JavaScript
var handleError = _.cond([
[error => error.code === 404, () => 'Not found'],
[error => error.code === 500, () => 'Internal server error'],
[() => true, () => 'Unknown error']
]);
console.log(handleError({ code: 404 }));

You can also try this code with Online Javascript Compiler
Run Code
Output:
'Not found'
Demonstrates using _.cond() for error handling based on error codes.
Frequently Asked Questions
How is _.cond() different from using multiple if-else statements?
_.cond() provides a more structured and declarative approach to handling conditional logic, which can enhance readability and organization compared to multiple if-else statements.
Can _.cond() handle asynchronous conditions or actions?
_.cond() is designed for synchronous operations. For asynchronous conditions or actions, you would need to handle promises or async functions separately.
Is there a limit to the number of condition-result pairs in _.cond()?
There's no specific limit to the number of pairs, but it's advisable to keep the number reasonable for maintainability and readability.
Conclusion
Lodash's _.cond() method offers an elegant solution for handling complex conditional logic, mapping conditions to corresponding actions in a readable and maintainable format. It's a valuable tool for organizing and simplifying conditional operations in your code.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.