Created
November 15, 2016 15:53
-
-
Save spiralx/c4e4c5a457440f997a5320c4891846ad to your computer and use it in GitHub Desktop.
Map sub-class that defines a default value for missing keys
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
/* 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