Created
January 27, 2021 15:18
-
-
Save opensussex/649e8b08e582b2b4215ba26373258499 to your computer and use it in GitHub Desktop.
little example of a double linkedList
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
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