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.
Arguments
initialRecord<string, any>- Initial key-value pairs for the store. Copied, not referenced.
Returns
Function — A settings function overloaded on argument shape: read, write, bulk-merge, or snapshot.
Examples
const settings = createSettings({ theme: "dark" });
settings("theme"); // "dark" — read
settings("locale", "en-IN"); // sets, returns settings
settings({ a: 1, b: 2 }); // merges, returns settings
settings(); // { theme: "dark", locale: "en-IN", a: 1, b: 2 }const settings = createSettings();
settings("a", 1)("b", 2); // chains, because writes return settings
const snapshot = settings();
snapshot.a = 999;
settings("a"); // 1 — the snapshot is a copyBranch on arguments.length first, then on typeof — a write of undefined still has to count as a write.
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.
Notes
Object.assign({}, initial)copies the caller's object into your own — otherwise mutatinginitialfrom outside would corrupt the store.- This is the jQuery
.attr/.cssshape. Load-bearing APIs that overload on argument type pay the price in debuggability — document the branches, and lean on types where you can.
Stuck? The javascript course covers everything this challenge needs.
- 1.writes then reads a single key
- 2.merges an object of entries
- 3.a no-argument call returns a copy
- 4.both write forms return the function for chaining
- 5.an unset key reads as undefined
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.