AniUI Academy

Overload one function by argument shape

mediumFunctions & Closures+250 XPPractice

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 copy

Branch 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 settings function itself so calls chain.

Notes

  • Object.assign({}, initial) copies the caller's object into your own — otherwise mutating initial from outside would corrupt the store.
  • This is the jQuery .attr/.css shape. 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.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.