DEV Community

Discussion on: Public Solving: Linked List and a train

Collapse
 
lexlohr profile image
Alex Lohr

That is too wonderful a chance to use ES6 generators to pass:

function* iterateLinkedList(start) {
    while (start) {
        yield start
        start = start.next
    }
}

function* filterLinkedList(iterator, filter) {
    for (const item of iterator) {
        if (filter(item)) { yield item }
    }
}

const linkedListForEach = (iterator, action) => {
    for (const item of iterator) {
        action(item)
    }
}

const iterateWagons = (start, actionFn, filterFn) => {
    linkedListForEach(
        filterLinkedList(
            iterateLinkedList(start),
            filterFn
        ),
        actionFn
    )
}
Enter fullscreen mode Exit fullscreen mode

This may be a bit more verbose than necessary, but it is very composable.

Also, Date objects coerce to their numeric timestamps when compared and Dates initialized from ISO dates have their hours/minutes/secods/milliseconds set to zero:

const todayLastYear = new Date()
todayLastYear.setFullYear(todayLastYear.getFullYear() - 1)

const filterOldBreaks = wagon => new Date(wagon.lastBrakeRevision || 0) < todayLastYear
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dailydevtips1 profile image
Chris Bongers

Oh man!

I was hoping to get a response from you on this task!
This is wonderful!

Learned something new here!
As linked list are really a new field to me.

Gonna give this another try with you example soon 👏