Skip to content

Commit

Permalink
feat: done list
Browse files Browse the repository at this point in the history
  • Loading branch information
nonzzz committed Aug 2, 2024
1 parent 8c12204 commit 7999166
Showing 1 changed file with 59 additions and 10 deletions.
69 changes: 59 additions & 10 deletions src/list.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,71 @@
class Elt {
constructor() {}
/* eslint-disable no-use-before-define */
class Elt <T> {
items: Array<T | undefined>
pos: number
mask: number
rev: number
next: Elt<T> | null
constructor(cap: number) {
this.items = new Array(cap)
this.pos = 0
this.rev = 0
this.mask = cap - 1
this.next = null
}

get leak() {
return this.items[this.pos] !== undefined
}

push() {}
push(element: T) {
this.items[this.pos] = element
this.pos = (this.pos + 1) & this.mask
}

shift() {}
shift() {
const first = this.items[this.rev]
if (first === undefined) return undefined
this.items[this.rev] = undefined
this.rev = (this.rev + 1) & this.mask
return first
}
}

export class List {
export class List<T> {
private cap: number
constructor(cap = 16) {
this.cap = cap
private head: Elt<T>
private tail: Elt<T>
length: number
constructor() {
this.cap = 16
this.length = 0
this.head = new Elt(this.cap)
this.tail = this.head
}

push() {
//
push(elt: T) {
if (this.head.leak) {
const prev = this.head
prev.next = new Elt(this.head.items.length * 2)
this.head = prev.next
}
this.head.push(elt)
this.length++
}

shift() {
//
if (this.length !== 0) this.length--
const value = this.tail.shift()
if (value === undefined && this.tail.next) {
const next = this.tail.next
this.tail.next = null
this.tail = next
return this.tail.shift()
}
return value
}
}

export function createList<T>() {
return new List<T>()
}

0 comments on commit 7999166

Please sign in to comment.