I want to generate a list of years that should be dynamic. I want to show the current year, previous 3 years and next 4 years along with an empty object at the start. The output should be [2020, 2021, 2022, 2023, 2023, 2024, 2025, 2026, 2027]
I have a working function, but I’m wondering if there is a more efficient / preferment approach. It feels like too much code for a simple function.
const generateYears = () => {
const previousYears = [...Array(4)].map(
(a, b) => new Date().getFullYear() - b,
);
const futureYears = [...Array(5)].map((a, b) => new Date().getFullYear() + b);
const years = new Set([...previousYears, ...futureYears].sort());
const yearsObj = [...years].map((year: number) => {
return {
value: year.toString(),
name: year.toString(),
};
});
yearsObj.unshift({
value: '',
name: '',
});
return yearsObj;
};
3
Answers
I would use a
range
helper function for that. Something like:See also
Just made this is different way using ES6,
able to create the array as required in single line but adding the same was made manually,
this is the exact format as shared in the example, modified as per the output of the question.
if it is all about array,
I will present a series of progressive refactorings, but here is the final code:
First, instead of creating multiple ranges, merging them, and deduplicating values, you can create a single range.
I would do this with a helper function, for clarity:
This creates an array of length
length
containing a sequence of numbers starting atstart
.With some other slight refactors (how the final array is constructed, etc.), that makes it something like this:
To make this more reusable, you could allow the "center" year and number of previous and future years to be passed as parameters:
If you mostly will use the current year as the "center", you could move that parameter to the end and make it optional:
Aside: If you want a more functional programming "feel", you could do it something like this:
(I arrived at this independently, but credit to @Kooilnc for getting there first.)