Skip to content

Instantly share code, notes, and snippets.

@spiralx
Created November 15, 2016 15:53
Show Gist options
  • Save spiralx/c4e4c5a457440f997a5320c4891846ad to your computer and use it in GitHub Desktop.
Save spiralx/c4e4c5a457440f997a5320c4891846ad to your computer and use it in GitHub Desktop.
Map sub-class that defines a default value for missing keys
/* jshint asi: true, esnext: true */
(() => {
'use strict'
// --------------------------------------------------------------------------
class DefaultMap extends Map {
get(key) {
return super.has(key)
? super.get(key)
: this.getDefault(key)
}
getDefault(key) {}
}
// --------------------------------------------------------------------------
class Counter extends DefaultMap {
getDefault(key) {
return 0
}
sortedItems() {
return Array.from(this.entries())
.sort((a, b) => (b[1] - a[1]) || a[0].localeCompare(b[0]))
}
}
// --------------------------------------------------------------------------
class Collector extends DefaultMap {
getDefault(key) {
return []
}
count(key) {
return this.get(key).length
}
}
// --------------------------------------------------------------------------
const c = new Counter()
Array.from(document.querySelectorAll('*')).forEach(elem => {
[...elem.classList].forEach(cls => {
c.set(cls, c.get(cls) + 1)
})
})
console.table(c.sortedItems())
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment