Created
April 22, 2018 08:34
-
-
Save Aleksey-Danchin/53a0972218699aa95f783b85f3c01854 to your computer and use it in GitHub Desktop.
prototype expansion
This file contains hidden or 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
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