Skip to content

Instantly share code, notes, and snippets.

@rsimpson2
Last active July 26, 2019 22:20
Show Gist options
  • Save rsimpson2/1931464353330367fdd7a9f121541955 to your computer and use it in GitHub Desktop.
Save rsimpson2/1931464353330367fdd7a9f121541955 to your computer and use it in GitHub Desktop.
Flexible Years
const data = [
{ fyStart: 'FY18', fyEnd: 'FY18' },
{ fyStart: 'FY18', fyEnd: 'FY20' },
{ fyStart: 'FY17', fyEnd: 'FY18' }
];
const start = data.map(d => d.fyStart.replace('FY', '')).sort();
const end = data.map(d => d.fyEnd.replace('FY', '')).sort();
const uniqueYears = Array.from(new Set([...start, ...end]));
let firstYear = uniqueYears[0] - 1; // this adds a year before the first year
let lastYear = uniqueYears[uniqueYears.length - 1];
let totalYears = 6; // we will show 6 years in the dyanmic data
var missingYears = [];
// data will come back with holes in the numbers, such as [18, 20]. Need to fill in missing years
for (let i = firstYear; i <= uniqueYears[uniqueYears.length - 1]; i++) {
if (uniqueYears.indexOf(i) === -1) {
missingYears.push(i);
}
}
// need to always have it at a minimum of 6 years, so we have to check that the array has 6 items
let fillExtraYears = totalYears - missingYears.length;
if (fillExtraYears > 0) {
for (let i = 1; i <= fillExtraYears; i++) {
missingYears.push(Number(lastYear) + i);
}
} else {
// oh no, way too many years, you are getting capped to 8 years
let extraYears = totalYears + 2;
missingYears.splice(extraYears);
}
console.log(missingYears); // [ 16, 17, 18, 19, 20, 21 ]
// if you change FY20 above to a higher number, such as FY23, you can test again and you will get
// [ 16, 17, 18, 19, 20, 21, 22, 23 ]
// this is the use case of where there could be more than 6 years so allow it to go to 8
// change to even higher number and see that it will always get set to no more than 8 years
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment