Created
May 9, 2022 13:58
-
-
Save nnnkit/4b9dfe006b088fbf69078cc7971c0803 to your computer and use it in GitHub Desktop.
Array implementation using Object
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 MyArray { | |
constructor(arr = []) { | |
this.value = arr.reduce((acc, cv, i) => { | |
acc[i] = cv | |
return acc | |
}, {}) | |
} | |
get length() { | |
return Object.keys(this.value).length | |
} | |
push(val) { | |
this.value[this.length] = val | |
return this.length | |
} | |
pop() { | |
delete this.value[this.length - 1] | |
return this.length | |
} | |
forEach(cb) { | |
let keys = Object.keys(this.value) | |
for (let i = 0; i < keys.length; i++) { | |
let key = keys[i] | |
const value = this.value[key] | |
cb(value) | |
} | |
} | |
} | |
let array = new MyArray([1, 2, 3]) | |
array.length // 3 | |
array.push(5) // 4 (returns the length of the array) | |
array.pop() // 5 | |
array.forEach((elm) => console.log(elm)) // logs 1, 2 and 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment