Last active
August 26, 2018 20:14
-
-
Save andrewborisov/7fb7b0ae88e218d94672136843357b20 to your computer and use it in GitHub Desktop.
infinite reverse month loop, which returns array of objects started from provided date minus one month
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const months = ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июнь', 'Июль', 'Авг', 'Сент', 'Окт', 'Ноя', 'Дек']; | |
const reverseMonthLoop = (date, iterations) => { | |
let titles = []; | |
const [d, m, y] = date.split('.'); | |
const reversedMonths = memoizedCalculateMonth(m, iterations); | |
reversedMonths.map(month => { | |
titles.push({ | |
month: months[month - 1], | |
year: memoizedCalculateYear({ m: month, d, y: y }), | |
}); | |
}); | |
return titles; | |
}; | |
const calculateMonth = () => { | |
let cached = 0; | |
let reversedMonths = []; | |
return (month, i) => { | |
if (i > cached) { | |
cached++; | |
if (month > 1) { | |
month--; | |
reversedMonths.push(month); | |
} else { | |
month = months.length; | |
reversedMonths.push(month); | |
} | |
memoizedCalculateMonth(month, i); | |
} | |
return reversedMonths; | |
} | |
}; | |
const calculateYear = () => { | |
let cache = []; | |
return (n) => { | |
if (cache.length > 0) { | |
const { m, d, y } = cache[cache.length-1]; | |
const memoizedDate = new Date(`${m}.${d}.${y}`); | |
const givenDate = new Date(`${n.m}.${n.d}.${y}`); | |
if (givenDate > memoizedDate) { | |
cache.push({ m:n.m, d:n.d, y: y-1 }); | |
return y-1; | |
} else { | |
cache.push({ m:n.m, d:n.d, y: y }); | |
return y; | |
} | |
} else { | |
if (n.m === 12) { | |
cache.push({ m: n.m, d: n.d, y: n.y-1}); | |
return n.y-1; | |
} else { | |
cache.push(n); | |
return n.y; | |
} | |
} | |
} | |
}; | |
const memoizedCalculateMonth = calculateMonth(); | |
const memoizedCalculateYear = calculateYear(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment