Skip to content

Instantly share code, notes, and snippets.

@nnnkit
Created May 9, 2022 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nnnkit/4b9dfe006b088fbf69078cc7971c0803 to your computer and use it in GitHub Desktop.
Save nnnkit/4b9dfe006b088fbf69078cc7971c0803 to your computer and use it in GitHub Desktop.
Array implementation using Object
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