Last active
August 11, 2022 09:36
-
-
Save naveenrawat51/df18a8477aace6ff08d1a6b26fce8ac5 to your computer and use it in GitHub Desktop.
Array implementation 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 Myarray { | |
constructor(size) { | |
(this.data = {}), (this.length = 0); | |
for (let i = 0; i < size; i++) { | |
this.data[i] = undefined; | |
this.length++; | |
} | |
} | |
push(item) { | |
this.data[this.length] = item; | |
this.length += 1; | |
return this.data; | |
} | |
pop() { | |
if (this.length) { | |
delete this.data[this.length - 1]; | |
this.length -= 1; | |
console.log(this.data, this.length); | |
return this.data; | |
} | |
return null; | |
} | |
map(callback) { | |
if (typeof callback === 'Function' || typeof callback === 'function') { | |
const result = {}; | |
for (let i = 0; i < this.length; i++) { | |
result[i] = callback(this.data[i], i, this.data); | |
} | |
return (this.data = result); | |
} | |
return null; | |
} | |
filter(callback) { | |
if (typeof callback === 'Function' || typeof callback === 'function') { | |
const result = {}; | |
let counter = 0; | |
for (let i = 0; i < this.length; i++) { | |
if (callback(this.data[i], i, this.data)) { | |
result[counter] = this.data[i]; | |
counter++; | |
} | |
} | |
return (this.data = result); | |
} | |
return []; | |
} | |
} | |
const array1 = new Myarray(); | |
array1.push(5); | |
array1.push(23); | |
array1.push(3); | |
array1.map((element) => element * 2); | |
array1.filter((element) => element > 10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How about delete and insert.