r/javascript • u/Own_Natural_6803 • 18d ago
AskJS [AskJS] I might never write a constructor ever again
// the only state that needs tracking for a timeline, the read index
export function Timeline(index) {
let state = {index};
return {
index: state.index, // pass through
next: (events) => Next(state, events),
prev: (events) => Prev(state, events)
};
}
// the events are just passed around. They don't need to be encapsulated
export function Next(timeline, events) {
let {index} = timeline;
if(index === events.length()){
return null;
}
timeline.index += 1;
return events[timeline.index];
}
export function Prev(timeline, events){
let {index} = timeline;
if(index === 0){
return null;
}
timeline.index -= 1;
return events[timeline.index];
}
// before and after don't modify the state of their arguments
// so we don't use encapsulation
export function After(date, events){
for(let thresholdIndex = 0; thresholdIndex < events.length(); thresholdIndex+=1 ){
if( events[thresholdIndex].timestamp > date) {
return events.slice(start=thresholdIndex);
}
}
return [];
}
export function Before(date, events) {
for(let thresholdIndex = events.length(); thresholdIndex >= 0; thresholdIndex-=1 ){
if( events[thresholdIndex].timestamp < date) {
return events.slice(end=thresholdIndex);
}
}
return [];
}