Skip to content

Instantly share code, notes, and snippets.

@think49
Last active September 13, 2021 13:20
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 think49/6776d8cebf8d4ca75c7b935aec4f4b82 to your computer and use it in GitHub Desktop.
Save think49/6776d8cebf8d4ca75c7b935aec4f4b82 to your computer and use it in GitHub Desktop.
const-map.js: 定義済みの `key` の `set()` した時にエラーを発生させる `new Map` 互換オブジェクトを生成します

const-map.js

概要

定義済みの keyset() した時にエラーを発生させる new Map 互換オブジェクトを生成します。

/**
* 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());
}
};
})();
<!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