Skip to content

Instantly share code, notes, and snippets.

@opensussex
Created January 27, 2021 15:18
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 opensussex/649e8b08e582b2b4215ba26373258499 to your computer and use it in GitHub Desktop.
Save opensussex/649e8b08e582b2b4215ba26373258499 to your computer and use it in GitHub Desktop.
little example of a double linkedList
const uuid = require('uuid/v1');
export default class DoubleLinkedList {
list;
currentItemId;
constructor(items) {
this.setList(items);
}
setList = items => {
let prevId = null;
let nextId = null;
let currentId = null;
this.list = items.map((item, i) => {
prevId = currentId;
currentId = nextId ? nextId : uuid();
nextId = i + 1 == items.length ? null : uuid();
return {
id: currentId,
prevId: prevId,
nextId: nextId,
item: item,
};
});
if (this.list[0] !== undefined) {
this.currentItemId = this.list[0].id;
}
};
getCurrent = () => {
return this.findById(this.currentItemId);
};
setCurrentToNext = () => {
const currentItem = this.getCurrent();
this.currentItemId = currentItem.nextId ? currentItem.nextId : this.currentItemId;
};
setCurrentToPrev = () => {
const currentItem = this.getCurrent();
this.currentItemId = currentItem.prevId ? currentItem.prevId : this.currentItemId;
};
findById = id => {
return this.list.find(i => i.id == id);
};
getList = () => {
return this.list;
};
setCurrentById = id => {
this.currentItemId = id;
};
setCurrentToFirst = () => {
if (this.list[0] !== undefined) {
this.currentItemId = this.list[0].id;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment