Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
map-prototype-sort.js: Array.prototype.sort 互換のメソッドを定義

map-prototype-sort.js

概要

Map.prototype.sortArray.prototype.sort 互換のメソッドを定義します。

使い方

Map.prototype.sort(comparefn)

第一引数に指定された比較関数を基準として、ソートした Map オブジェクトを返します。

var map = new Map([['a',2],['b',1],['c',3]]).sort((a,b) => a[1] - b[1]);

console.log(JSON.stringify([...map]));	// [["b",1],["a",2],["c",3]]

Map.prototype.sort は破壊的です。

var map = new Map([[3, 'c'],[2, 'b'],[4, 'd'],[1, 'a']]);

map.sort((a,b) => a[0] - b[0]);
console.log(JSON.stringify([...map]));	// [[1,"a"],[2,"b"],[3,"c"],[4,"d"]]
/**
* map-prototype-sort-1.0.0.js
* Sort map object.
*
* @version 1.0.0
* @author think49
* @url https://gist.github.com/think49/daaf5ee0a4f12092862c81c54747bae5
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
*/
if (typeof Map === 'function' && !('sort' in Map.prototype) && typeof Object.defineProperties === 'function') {
Object.defineProperties(Map.prototype, {sort: {
writable: true,
enumerable: false,
configurable: true,
value: function sort (comparefn) {
var entries = [...this.entries()].sort(comparefn);
this.clear();
for (let [key, value] of entries) {
this.set(key, value);
}
return this;
}
}});
}
<!DOCTYPE html>
<head>
<title>test</title>
<style>
</style>
</head>
<body>
<script src="map-prototype-sort-1.0.0.js"></script>
<script>
'use strict';
console.assert(JSON.stringify([...new Map([['a',2],['b',1],['c',3]]).sort((a,b) => a[1] - b[1])]) === '[["b",1],["a",2],["c",3]]');
var map = new Map([[3, 'c'],[2, 'b'],[4, 'd'],[1, 'a']]);
map.sort((a,b) => a[0] - b[0]);
console.assert(JSON.stringify([...map]) === '[[1,"a"],[2,"b"],[3,"c"],[4,"d"]]');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.