Exercise 20: Function Validator (input validation)
Problem Statement
Create a function `withValidation(fn, validator)` that validates function inputs before execution.
Sample Output:
const validated = withValidation((x) => x * 2, (x) => typeof x === "number");
validated(5) => 10
validated("5") => throws Error("Validation failed")Solution
const withValidation = (fn, validator) => {
return (...args) => {
if (!validator(...args)) throw new Error("Validation failed");
return fn(...args);
};
};Explanation
Overall Goal:
- Function inputs ko validate karna before execution.
Real world:
- Type safety: runtime validation.
- API contracts: input validation.
Navigation
Previous
Exercise 19
Next
No next exercise
Category
Functions & Patterns
20 Exercises