-
-
Save WimJongeneel/42386fc8e2544a79c4fc3adf6a7fc1e5 to your computer and use it in GitHub Desktop.
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
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