function filter(elements, filters, type) {
    const compareDate = (dateA, dateB) => {
        const dA = new Date(dateA);
        const dB = new Date(dateB);

        if (filters.yearOrder === "asc") {
            return dA - dB;
        } else {
            return dB - dA;
        }
    };

    return [...elements].sort((a, b) => {
        let timeComparison;

        if (filters.yearOrder !== null) {
            if (type === "event") {
                timeComparison = compareDate(a.start, b.start);
            }

            else if (type === "user") {
                timeComparison = compareDate(a.created_at, b.created_at);
            }

            if (timeComparison !== 0 && timeComparison !== undefined) {
                return timeComparison;
            }
        }

        if (filters.alphabetical !== null) {
            return filters.alphabetical === "asc"
                ? a.name.localeCompare(b.name)
                : b.name.localeCompare(a.name);
        }

        return 0;
    });
}

export default filter;
