Last active
August 23, 2022 07:56
-
-
Save stephane-vanraes/279105f66c246cda0722c53773b964df to your computer and use it in GitHub Desktop.
Hash with default value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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