Last active
September 30, 2023 13:41
-
-
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*
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
// 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