Singleton settings store shared via getInstance and new
A web app reads its settings (theme, locale, feature toggles) from many modules. If each module created its own settings object, a change made in one place would be invisible everywhere else. The Singleton pattern solves this: there is exactly one instance, and every caller gets that same instance.
Implement a class SettingsStore that follows the Singleton pattern.
SettingsStore.getInstance(): a static method that returns the single instance. It creates the instance on the first call.new SettingsStore(): also returns that same instance. If no instance exists yet, it becomes the instance.store.set(key, value): saves value under key and returns the store, so calls can be chained.store.get(key): returns the saved value, or undefined if key was never set (or was deleted).store.has(key): returns true if key is set, even when its value is falsy (0, '', false, null, undefined).store.delete(key): removes key. Returns true if it was set, otherwise false.getInstance() and every new SettingsStore() returns the same object, and it is an instanceof SettingsStore.'toString', 'constructor', or 'hasOwnProperty' are ordinary keys: they are not set until you set them.const settings = SettingsStore.getInstance();
settings.set('theme', 'dark').set('locale', 'en-GB');
const sameSettings = new SettingsStore();
sameSettings === settings; // => true
sameSettings.get('theme'); // => 'dark'
settings.set('betaBanner', false);
settings.has('betaBanner'); // => true
settings.get('fontSize'); // => undefined
settings.has('toString'); // => false
settings.delete('locale'); // => true
settings.delete('locale'); // => false
Your class is loaded once, and the tests may run in any order against the same instance. Each test uses its own keys.