Skip to content

Instantly share code, notes, and snippets.

@tsmx
Last active September 30, 2023 13:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsmx/d385e428c00c527d388d441a4c27201a to your computer and use it in GitHub Desktop.
Save tsmx/d385e428c00c527d388d441a4c27201a to your computer and use it in GitHub Desktop.
sorted-iterable-map: iterate with a for-loop over a JavaScript Map sorted by value attributes with a custom iterator using function* and yield*
// In the example: sort descending by 'activeUsers' attribute of the value object
var countries = new Map();
countries.set('DE', { name: 'Germany', activeUsers: 15000 });
countries.set('PL', { name: 'Poland', activeUsers: 13900 });
countries.set('UK', { name: 'United Kingdom', activeUsers: 14500 });
console.log('without iterator:');
for (let [key, info] of countries) {
console.log(key + ' - ' + info.name + ', ' + info.activeUsers);
}
// DE - Germany, 15000
// PL - Poland, 13900
// UK - United Kingdom, 14500
// *** Here comes the magic :) ***
countries[Symbol.iterator] = function* () {
yield* [...countries.entries()].sort((a, b) => b[1].activeUsers - a[1].activeUsers);
}
console.log('with custom iterator:');
for (let [key, info] of countries) {
console.log(key + ' - ' + info.name + ', ' + info.activeUsers);
}
// DE - Germany, 15000
// UK - United Kingdom, 14500
// PL - Poland, 13900
// Adding an antry to the map and check if sorting is still valid
countries.set('IT', { name: 'Italy', activeUsers: 14200 });
console.log('after adding an entry:');
for (let [key, info] of countries) {
console.log(key + ' - ' + info.name + ', ' + info.activeUsers);
}
// DE - Germany, 15000
// UK - United Kingdom, 14500
// IT - Italy, 14200
// PL - Poland, 13900
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment