定義済みの key
の set()
した時にエラーを発生させる new Map
互換オブジェクトを生成します。
Last active
September 13, 2021 13:20
-
-
Save think49/6776d8cebf8d4ca75c7b935aec4f4b82 to your computer and use it in GitHub Desktop.
const-map.js: 定義済みの `key` の `set()` した時にエラーを発生させる `new Map` 互換オブジェクトを生成します
This file contains 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
/** | |
* const-map-0.1.1.js | |
* | |
* | |
* @version 0.1.1 | |
* @author think49 | |
* @url https://gist.github.com/think49/6776d8cebf8d4ca75c7b935aec4f4b82 | |
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License) | |
*/ | |
'use strict'; | |
const ConstMap = (()=>{ | |
const privateMap = new WeakMap; | |
return class ConstMap { | |
constructor (...params) { | |
privateMap.set(this, new Map(...params)); | |
} | |
get (key) { | |
return privateMap.get(this).get(key); | |
} | |
set (key, value) { | |
const map = privateMap.get(this); | |
const defError = new Error; | |
defError.name = 'DefinitionError'; | |
defError.message = 'Identifier \'' + key + '\' has already been declared'; | |
if (map.has(key)) throw defError; | |
return map.set(key, value); | |
} | |
has (key) { | |
return privateMap.get(this).has(key); | |
} | |
keys () { | |
return Array.from(privateMap.get(this).keys()); | |
} | |
values () { | |
return Array.from(privateMap.get(this).values()); | |
} | |
entries () { | |
return Array.from(privateMap.get(this).entries()); | |
} | |
}; | |
})(); |
This file contains 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
<!DOCTYPE html> | |
<title>test</title> | |
<style> | |
</style> | |
<script src="./const-map-0.1.1.js"></script> | |
<script> | |
'use strict'; | |
const cmap = new ConstMap([['foo',1],['bar',2],['baz',3]]); | |
/** | |
* Assertion | |
*/ | |
console.assert(cmap.get('foo') === 1); | |
console.assert(cmap.get('bar') === 2); | |
console.assert(cmap.get('baz') === 3); | |
console.assert(cmap.get('qux') === undefined); | |
console.assert(cmap.has('foo') === true); | |
console.assert(cmap.has('bar') === true); | |
console.assert(cmap.has('baz') === true); | |
console.assert(cmap.has('qux') === false); | |
console.assert(JSON.stringify(cmap.keys()) === '["foo","bar","baz"]'); | |
console.assert(JSON.stringify(cmap.values()) === '[1,2,3]'); | |
console.assert(JSON.stringify(cmap.entries()) === '[["foo",1],["bar",2],["baz",3]]'); | |
</script> | |
<script> | |
/** | |
* DefinitionError | |
*/ | |
cmap.set('foo', false); // DefinitionError: Identifier 'foo' has already been declared | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment