Skip to content

Instantly share code, notes, and snippets.

@WimJongeneel
Last active June 11, 2020 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WimJongeneel/42386fc8e2544a79c4fc3adf6a7fc1e5 to your computer and use it in GitHub Desktop.
Save WimJongeneel/42386fc8e2544a79c4fc3adf6a7fc1e5 to your computer and use it in GitHub Desktop.
export interface Position<T> {
value: T
}
interface Node<T> extends Position<T> {
index: number
}
interface PositionalList<T> {
first(): Position<T>
last(): Position<T>
elementAt(index: number): Position<T>
before(p: Position<T>): Position<T>
after(p: Position<T>): Position<T>
append(value:T): void
prepend(value: T): void
set(value: T, p: Position<T>): void
remove(p: Position<T>): void
}
const list= <T extends any>(): PositionalList<T> => {
const data : T[] = []
return {
first: () => ({ value: data[0], index: 0 }),
last: () => ({ value: data[data.length-1], index: data.length - 1 }),
elementAt: i => ({ value: data[0], index: i}),
before: p => {
const index = (p as Node<T>).index - 1
return { value: data[index], index }
},
after: p => {
const index = (p as Node<T>).index + 1
return { value: data[index], index }
},
prepend: v => data.unshift(v),
append: v => data.push(v),
set: (v, p) => data[(p as Node<T>).index] = v,
remove: p => {
const index = (p as Node<T>).index + 1
data.splice(index, 1)
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment