Skip to content

Instantly share code, notes, and snippets.

@naveenrawat51
Last active August 11, 2022 09:36
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 naveenrawat51/df18a8477aace6ff08d1a6b26fce8ac5 to your computer and use it in GitHub Desktop.
Save naveenrawat51/df18a8477aace6ff08d1a6b26fce8ac5 to your computer and use it in GitHub Desktop.
Array implementation in javascript
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);
@Shedrack-Sunday
Copy link

How about delete and insert.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment