Multiplier function using closure

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-04-29

Problem Statement

Design and implement a multiplier function using closures that allows dynamic creation of functions to multiply numbers by a given factor.


This exercise tests understanding of:


•Functional programming concepts
•Closures and lexical scoping
•Encapsulation of state without using classes


📋 Problem Description


You are required to implement a function factory that creates multiplier functions.


For example:


•Calling createMultiplier(2) should return a function that multiplies any given number by 2.
•Similarly, createMultiplier(5) should return a function that multiplies numbers by 5.


You must ensure that each returned function remembers its multiplier value (closure behavior) even after the original scope has finished execution.


🧱 Core Requirements


1. Function Definition


Implement a higher-order function:

1 2def createMultiplier(factor): 3 # returns a function that multiplies input by 'factor'


2. Closure Behavior


The returned function should remember the factor value passed during its creation, even if used later.


3. Usage Example

1 2 3times2 = createMultiplier(2) 4times5 = createMultiplier(5) 5 6print(times2(10)) # Output: 20 7print(times5(10)) # Output: 50


⚙️ Functional Requirements


1.Support creation of multiple independent multiplier functions.
2.Ensure encapsulation — the factor cannot be directly modified externally.
3.Validate input — handle cases where the factor or input is not a number.
4.Demonstrate closure — show that the function retains access to its defining scope.


🧩 Example Scenario

1 2def createMultiplier(factor): 3 def multiplier(x): 4 return x * factor 5 return multiplier 6 7times3 = createMultiplier(3) 8times10 = createMultiplier(10) 9 10print(times3(7)) # Output: 21 11print(times10(7)) # Output: 70


⚙️ Non-Functional Requirements


Aspect and Requirement


Encapsulation

Multiplier value (factor) must not be exposed globally.


Reusability

The function should work for any valid numeric multiplier.


Immutability

The multiplier constant inside closure should remain unchanged.


Simplicity

No use of global variables or classes.


🧠 Design Discussion Points


•How does the closure retain access to the factor variable?
•Can this logic be extended to build other function factories (e.g., adder, power, etc.)?
•What happens if the returned function is assigned to multiple variables?


✅ Deliverables



•Implementation of createMultiplier(factor) function.
•Demonstration script showing closure behavior.
•Unit tests for multiple multipliers and invalid inputs.


🚀 Stretch Goals


•Extend to handle floating-point precision or decimal inputs.
•Add a decorator to log each multiplication operation.
•Convert it into a class-based equivalent and compare approaches.


Solution

Comments