Skip to content

Instantly share code, notes, and snippets.

@Aleksey-Danchin
Created April 22, 2018 08:34
Show Gist options
  • Save Aleksey-Danchin/53a0972218699aa95f783b85f3c01854 to your computer and use it in GitHub Desktop.
Save Aleksey-Danchin/53a0972218699aa95f783b85f3c01854 to your computer and use it in GitHub Desktop.
prototype expansion
Object.defineProperty(Array.prototype, 'first', {
get () {
return this[0]
},
set (val) {
if (!this.length) {
this.push(val)
return val
}
this[0] = val
return val
}
})
Object.defineProperty(Array.prototype, 'last', {
get () {
if (!this.length) {
return undefined
}
return this[this.length - 1]
},
set (val) {
if (!this.length) {
this.push(val)
return val
}
this[this.length - 1] = val
return val
}
})
Object.defineProperty(Array.prototype, 'max', {
get () {
if (!this.length) {
return undefined
}
return Math.max(...this)
},
set (val) {
if (!this.length) {
this.push(val)
return val
}
const max = Math.max(...this)
const index = this.indexOf(max)
this[index] = val
return val
}
})
Object.defineProperty(Array.prototype, 'min', {
get () {
if (!this.length) {
return undefined
}
return Math.min(...this)
},
set (val) {
if (!this.length) {
this.push(val)
return val
}
const min = Math.min(...this)
const index = this.indexOf(min)
this[index] = val
return val
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment