Exercise 3: Merge Defaults (without mutation)

Problem Statement

Function `withDefaults(config, defaults)` banao. Config overrides defaults. New object return karo.

Sample Output:

withDefaults({b: 20}, {a: 1, b: 2}) => {a: 1, b: 20}
withDefaults({}, {x: 10}) => {x: 10}

Solution

const withDefaults = (config, defaults) => ({ ...defaults, ...config });

Explanation

Overall Goal:

  • Defaults aur config ko merge karna.
  • Config values defaults ko override karengi.
  • New object return (mutation avoid).

Single Line Solution:

  • const withDefaults = (config, defaults) => ({ ...defaults, ...config });

Part 1: Spread defaults

  • { ...defaults } → defaults object ko spread karo:
  • ... → spread operator: object ke properties ko copy karta hai.
  • Example: {...{a: 1, b: 2}}{a: 1, b: 2}.

Part 2: Override with config

  • ...config → config object ko spread karo:
  • Agar same key hai → config value override karegi.
  • Agar new key hai → add ho jayegi.

Spread order matters:

  • {...defaults, ...config} → defaults pehle, config baad:
  • Same keys → config wins (override).
  • Different keys → dono merge ho jayengi.

Example:

  • withDefaults({b: 20}, {a: 1, b: 2}){a: 1, b: 20}.
  • b override ho gaya, a default se aaya.

Real world:

  • Feature flags: defaults + user config merge.
  • Settings: default values + user preferences.
  • Component props: default props + passed props.