dates | sum a list of events | display recurrence line graph | Search

The filterDistant function takes a list of events and a time threshold, returning a new list containing only events that are within the specified time window from the previous event.

Run example

npm run import -- "Number of days between events"

Number of days between events

// subtract the events from the previous one
function filterDistant(events, days = 28) {
    var contributing = [];
    events.sort((a, b) => a.start - b.start);
    events.forEach((e, i) => {
        if (i == 0) {
            return;
        }
        var diff = (e.start.getTime() - events[i - 1].start.getTime())
            / 1000 / 60 / 60 / 24;
        // if it is greater than 1 months it can't help our graph
        if (diff < days && diff > 0) {
            contributing[contributing.length] = {
                days: diff,
                start: e.start,
                event: e.event,
                i: contributing.length
            };
        }
    });
    return contributing;
};
module.exports = filterDistant;

    

What the code could have been:

/**
 * Filters events by removing distant ones.
 *
 * @param {Object[]} events - Array of events with start and event properties.
 * @param {number} [days=28] - Number of days within which an event is considered recent.
 * @returns {Object[]} Contributing events, sorted by their date.
 */
function filterDistant(events, days = 28) {
    // Check if the input array is empty or has only one element
    if (events.length < 2) {
        return events.length === 0? [] : events;
    }

    // Sort events by their start date in ascending order
    const sortedEvents = events.slice().sort((a, b) => a.start - b.start);

    // Initialize an array to store contributing events
    const contributing = [];

    // Iterate over the sorted events
    for (let i = 1; i < sortedEvents.length; i++) {
        // Calculate the difference in days between the current event and the previous one
        const diff = Math.round((sortedEvents[i].start.getTime() - sortedEvents[i - 1].start.getTime()) / (1000 * 60 * 60 * 24));

        // Check if the difference is within the specified range
        if (diff > 0 && diff <= days) {
            contributing.push({
                days: diff,
                start: sortedEvents[i].start,
                event: sortedEvents[i].event,
                index: contributing.length
            });
        }
    }

    return contributing;
}

module.exports = filterDistant;

This JavaScript code defines a function called filterDistant that filters a list of events based on a specified time threshold.

Here's a breakdown:

  1. Function Definition:

  2. Initialization:

  3. Sorting Events:

  4. Filtering Logic:

  5. Return Filtered Events:

  6. Module Export:

In essence, this code filters a list of events, keeping only those that are within a specified time window (defaulting to 28 days) from the previous event.