Skip to content

Instantly share code, notes, and snippets.

@zakuroishikuro
Created November 20, 2022 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zakuroishikuro/6da4f5e1a5a58617621a5837d2646af2 to your computer and use it in GitHub Desktop.
Save zakuroishikuro/6da4f5e1a5a58617621a5837d2646af2 to your computer and use it in GitHub Desktop.
const defaultDict = <T>(defaultValue: T, object = {}): { [key: string]: T } => {
return new Proxy(object, {
get(obj, prop) {
return prop in obj ? obj[prop] : defaultValue;
},
});
};
const dict = defaultDict(100);
dict.a = 1;
dict.a++;
dict.b /= 10;
console.log(`結果: ${dict.a}, ${dict.b}, ${dict.c}`);
//=> 結果: 2, 10, 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment