Skip to content

Instantly share code, notes, and snippets.

@stephane-vanraes
Last active August 23, 2022 07:56
Show Gist options
  • Save stephane-vanraes/279105f66c246cda0722c53773b964df to your computer and use it in GitHub Desktop.
Save stephane-vanraes/279105f66c246cda0722c53773b964df to your computer and use it in GitHub Desktop.
Hash with default value
function defHash(options, def) {
return new Proxy(options, {
get(target, prop) {
if (prop == 'has') return val => {
if (val === null) val = 'null'
if (val === undefined) val = 'undefined'
return target.hasOwnProperty(v.toString())
}
else return target[prop] ?? def;
}
})
}
let map = defHash({
0: 'Text 0',
1: 'Text 1',
2: 'Text 2'
}, 'default text');
console.log(map[0]); // 'Text 0'
console.log(map[1]); // 'Text 1'
console.log(map[2]); // 'Text 2'
console.log(map[3]); // 'default text'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment