|
| 1 | +class myArray<T> { |
| 2 | + private length: number; |
| 3 | + private data: {}; |
| 4 | + |
| 5 | + public constructor(args?: T[]) { |
| 6 | + this.length = args.length; |
| 7 | + this.data = {}; |
| 8 | + for (const key in args) { |
| 9 | + this.data[key] = args[key]; |
| 10 | + } |
| 11 | + } |
| 12 | + |
| 13 | + public size(): number { |
| 14 | + return this.length; |
| 15 | + } |
| 16 | + |
| 17 | + public isEmpty(): boolean { |
| 18 | + return this.length === 0; |
| 19 | + } |
| 20 | + |
| 21 | + public get(index: number): number { |
| 22 | + return this.data[index]; |
| 23 | + } |
| 24 | + |
| 25 | + public push(item: T): number { |
| 26 | + this.data[this.length] = item; |
| 27 | + this.length++; |
| 28 | + return this.length; |
| 29 | + } |
| 30 | + |
| 31 | + public pop(): T { |
| 32 | + const lastItem = this.data[this.length - 1]; |
| 33 | + delete this.data[this.length - 1]; |
| 34 | + this.length--; |
| 35 | + return lastItem; |
| 36 | + } |
| 37 | + |
| 38 | + public insert(index: number, item: T): object { |
| 39 | + for (let i = this.length; i >= index; i--) { |
| 40 | + this.data[i] = this.data[i - 1]; |
| 41 | + } |
| 42 | + this.data[index] = item; |
| 43 | + this.length++; |
| 44 | + return this.data; |
| 45 | + } |
| 46 | + |
| 47 | + public prepend(item: T): object { |
| 48 | + return this.insert(0, item); |
| 49 | + } |
| 50 | + |
| 51 | + public delete(index: number): T { |
| 52 | + const item = this.data[index]; |
| 53 | + this.shiftItems(index); |
| 54 | + return item; |
| 55 | + } |
| 56 | + |
| 57 | + private shiftItems(index: number): void { |
| 58 | + for (let i = index; i < this.length - 1; i++) { |
| 59 | + this.data[i] = this.data[i + 1]; |
| 60 | + } |
| 61 | + delete this.data[this.length - 1]; |
| 62 | + this.length--; |
| 63 | + } |
| 64 | +} |
0 commit comments