Last active
June 7, 2018 16:59
-
-
Save MKRhere/b9cb63dad56432c85c14ebafdedff59d to your computer and use it in GitHub Desktop.
Array-like custom class in JavaScript
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
class ArrayLike { | |
constructor (...items) { | |
if(items.length === 1 && !isNaN(items[0])) | |
for(let i = 0; i < items[0]; i++) { | |
this[i] = undefined; | |
} | |
else items.forEach((item, index) => this[index] = item); | |
return new Proxy(this, { | |
get: (obj, key) => { | |
if(key in obj) return obj[key]; | |
if(key === 'length') return Object.keys(this).length; | |
}, | |
set: (obj, key, value) => obj.key = value | |
}) | |
} | |
toString () { | |
return `[ ${Object.keys(this).map(x => this[x]).join(', ')} ]`; | |
} | |
} | |
const { log } = console; | |
const arr = new ArrayLike(5, 10); | |
log(arr.length); //-> 2 | |
console.log(arr + arr); //-> [ 5, 10 ][ 5, 10 ] | |
const arr2 = new ArrayLike(5); | |
log(arr2.length); //-> 5 | |
log(arr2 + arr2); //-> [ , , , , , ][ , , , , , ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment