-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
59 additions
and
10 deletions.
There are no files selected for viewing
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
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>() | ||
} |