Skip to content

Instantly share code, notes, and snippets.

@alex-taxiera
Last active May 15, 2019 02:07
Show Gist options
  • Save alex-taxiera/bcc99458bdb3a71dcb18f78d40518e31 to your computer and use it in GitHub Desktop.
Save alex-taxiera/bcc99458bdb3a71dcb18f78d40518e31 to your computer and use it in GitHub Desktop.
A Map class with some extra features for iterating.
class ExtendedMap extends Map {
constructor (iter) {
super(iter)
this._array = null
}
set (key, val) {
this._array = null
return super.set(key, val)
}
delete (key) {
this._array = null
return super.delete(key)
}
array () {
if (!this._array) {
this._array = Array.from(this.values())
}
return this._array
}
random (count) {
const arr = this.array()
if (!count) {
return arr[Math.floor(Math.random() * arr.length)]
}
if (arr.length === 0) {
return []
}
arr = arr.slice()
const rand = new Array(count)
for (let i = 0; i < count; i++) {
rand[i] = arr.splice(Math.floor(Math.random() * arr.length), 1)[0]
}
return rand
}
first (count) {
if (!count) {
return this.values().next().value
}
if (count < 0) {
return this.last(count * -1)
}
count = Math.min(this.size, count)
const arr = new Array(count)
const items = this.values()
let i = 0
while (i++ < count) {
arr[i] = items.next().value
}
return arr
}
last (count) {
const arr = this.array()
if (!count) {
return arr[arr.length - 1]
}
if (count < 0) {
return this.first(count * -1)
}
return arr.slice(-count)
}
find (fn) {
for (const item of this.values()) {
if (fn(item)) {
return item
}
}
}
some (fn) {
let i = 0
for (const item of this.values()) {
if (fn(item, i++, this)) {
return true
}
}
return false
}
every (fn) {
let i = 0
for (const item of this.values()) {
if (!fn(item, i++, this)) {
return false
}
}
return true
}
reduce (fn, ax) {
const items = this.values()
let i = 0
if (arguments.length === 1) {
ax = items.next().value
i++
}
for (const item of items) {
ax = fn(ax, item, i++, this)
}
return ax
}
map (fn) {
return this.reduce(
(ax, dx, cx, map) => {
ax[cx] = fn(dx, cx, map)
return ax
},
new Array(this.size)
)
}
filter (fn) {
return this.reduce(
(ax, dx, cx, map) => {
if (fn(dx, cx, map)) {
ax.push(dx)
}
return ax
},
[]
)
}
}
module.exports = ExtendedMap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment