Skip to content

Instantly share code, notes, and snippets.

@TheLucifurry
Created June 3, 2024 12:53
Show Gist options
  • Select an option

  • Save TheLucifurry/a115bc0d9c7415a22f65856117d4e6ac to your computer and use it in GitHub Desktop.

Select an option

Save TheLucifurry/a115bc0d9c7415a22f65856117d4e6ac to your computer and use it in GitHub Desktop.
import type { Ref } from 'vue'
import { computed, ref } from 'vue'
export function useList<T>(initialValue: T[] = []) {
const items = ref(initialValue) as Ref<T[]>
const isEmpty = computed(() => items.value.length === 0)
const size = computed(() => items.value.length)
function enqueue(item: T) {
items.value.push(item)
}
function dequeue(): T | null {
return isEmpty.value ? null : items.value.shift()!
}
function front(): T | null {
return isEmpty.value ? null : items.value[0]
}
function rear(): T | null {
return isEmpty.value ? null : items.value.at(-1)!
}
function at(index: number): T | null {
return items.value.at(index) ?? null
}
function has(item: T): boolean {
return items.value.includes(item)
}
function insert(index: number, item: T): void {
// TODO: test it
if (index >= 0 && index <= size.value)
items.value.splice(index, 0, item)
}
function remove(index: number): T | null {
// TODO: test it
if (index >= 0 && index < size.value)
return items.value.splice(index, 1)[0] || null
return null
}
function clear() {
items.value = []
}
return {
items,
isEmpty,
enqueue,
dequeue,
front,
rear,
at,
has,
insert,
remove,
size,
clear,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment