Give Missing Properties a Default

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write withDefault(target, fallback): return a Proxy around the object target. Reading a property that target doesn't have, own or inherited, gives fallback instead of undefined. A property target does have gives its own value, even when that's 0, an empty string, false, null or undefined. Writes go straight through to target, and the proxy adds no keys of its own: Object.keys and the in operator see exactly what target has. So with const counts = withDefault({}, 0), counts.apple += 1 makes target { apple: 1 }.

Your code must pass

  • Returns the fallback for missing properties
  • Keeps values that exist, even falsy ones
  • Writes go through to the original object
  • Doesn't add keys