Skip to content

Instantly share code, notes, and snippets.

@heypoom
Created July 22, 2019 11:31
Show Gist options
  • Save heypoom/90dbf830077bdaf52f1b9e2f4bfbae99 to your computer and use it in GitHub Desktop.
Save heypoom/90dbf830077bdaf52f1b9e2f4bfbae99 to your computer and use it in GitHub Desktop.
Simple Linked List in TypeScript.
const VecNode = (value?: any) => ({
value,
next: null
})
function Vec() {
let _node = VecNode()
let length = 0
return {
_node,
get(idx: number) {
let n = this._node
if (idx > length + 1) return null
for (let i = 0; i < idx; i++) {
if (!n) return null
n = n.next
}
if (!n) return null
return n.value
},
toString() {
let idx = length
let str = ''
let n = this._node
if (idx > length + 1) return null
for (let i = 0; i < idx; i++) {
str += `${n.value}${i === idx - 1 ? '' : ', '}`
n = n.next
}
return `Vec(${str})`
},
inspect() {
return this.toString()
},
length,
push(item) {
if (length === 0) {
_node.value = item
return length++
}
_node.next = VecNode(item)
_node = _node.next
return length++
},
pop() {
let idx = length - 1
const item = this.get(idx)
let n = this._node
if (idx > length + 1) return null
for (let i = 0; i < idx - 1; i++) {
n = n.next
}
n.next = null
if (length > 0) {
length--
}
if (length === 0) {
_node.value = null
return item
}
_node = n
if (!n) return null
return item
}
}
}
const v = Vec()
v
v.push(5)
v
v.push(10)
v
v.get(0) //?
v.push(20)
v //?
v.length //?
v
v.pop() //?
v
v.get(0) //?
v.get(1) //?
v.push(30)
v.get(0) //?
v.get(1) //?
v.get(2) //?
v.get(3) //?
v.get(4) //?
v.pop() //?
v.pop() //?
v.pop() //?
v.pop() //?
v.push('SSJ')
v.push('112')
v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment