Overload one function by argument shape
JavaScript has no real overloading, so libraries fake it by inspecting arguments: attr("href") reads, attr("href", url) writes, attr({ ... }) writes many. Done carelessly this is a mess; done deliberately it is a genuinely pleasant API, and writing one teaches you to branch on argument count and type rather than on a flag.
Implement createSettings(initial = {}). It returns a *function* settings that closes over the store and behaves four ways. Called with no arguments, it returns a shallow copy of the whole store, so mutating the returned object does not change the store. Called with one string, it returns that key's value, or undefined if the key was never set. Called with a string and a second argument, it sets that key to that value and returns the settings function itself, so writes can be chained. Called with one plain object, it merges those entries into the store, overwriting existing keys, and also returns the settings function itself.
What it has to do
- One string argument reads a value; an unset key gives
undefined. - A string plus a value writes that key.
- A single object argument merges its entries into the store.
- No arguments returns a shallow copy that callers cannot use to mutate the store.
- Both write forms return the
settingsfunction itself so calls chain.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.