Exercise 15: Function Overloading (simulate)

Problem Statement

Create a function `overload(...handlers)` that executes different handlers based on different argument types.

Sample Output:

const fn = overload(
  {match: (x) => typeof x === "string", fn: (x) => x.toUpperCase()},
  {match: (x) => typeof x === "number", fn: (x) => x * 2}
);
fn("hello") => "HELLO"
fn(5) => 10

Solution

const overload = (...handlers) => {
  return (...args) => {
    for (const handler of handlers) {
      if (handler.match(...args)) return handler.fn(...args);
    }
    throw new Error("No matching handler");
  };
};

Explanation

Overall Goal:

  • Function overloading simulate karna.

Real world:

  • API design: flexible function signatures.
  • Type handling: different input types.