Skip to content

Commit

Permalink
refactor(list_archives): Reduce calls to date.format()
Browse files Browse the repository at this point in the history
  • Loading branch information
dailyrandomphoto committed Dec 26, 2019
1 parent 75fea56 commit cdea2aa
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/plugins/helper/list_archives.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ function listArchivesHelper(options = {}) {
const showCount = Object.prototype.hasOwnProperty.call(options, 'show_count') ? options.show_count : true;
const className = options.class || 'archive';
const order = options.order || -1;
const compareFunc = type === 'monthly'
? (yearA, monthA, yearB, monthB) => yearA === yearB && monthA === monthB
: (yearA, monthA, yearB, monthB) => yearA === yearB;

let result = '';

if (!format) {
Expand All @@ -30,14 +34,14 @@ function listArchivesHelper(options = {}) {
let date = post.date.clone();

if (timezone) date = date.tz(timezone);
if (lang) date = date.locale(lang);

const year = date.year();
const month = date.month() + 1;
const name = date.format(format);
const lastData = data[length - 1];

if (!lastData || lastData.name !== name) {
if (!lastData || !compareFunc(lastData.year, lastData.month, year, month)) {
if (lang) date = date.locale(lang);
const name = date.format(format);
length = data.push({
name,
year,
Expand Down
28 changes: 28 additions & 0 deletions test/scripts/helpers/list_archives.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,19 @@ describe('list_archives', () => {
].join(''));
});

it('show_count + style: false', () => {
const result = listArchives({
style: false,
show_count: false
});

result.should.eql([
'<a class="archive-link" href="/archives/2014/02/">February 2014</a>',
'<a class="archive-link" href="/archives/2013/10/">October 2013</a>',
'<a class="archive-link" href="/archives/2013/06/">June 2013</a>'
].join(', '));
});

it('order', () => {
const result = listArchives({
order: 1
Expand Down Expand Up @@ -123,6 +136,21 @@ describe('list_archives', () => {
].join(''));
});

it('transform + style: false', () => {
const result = listArchives({
style: false,
transform(str) {
return str.toUpperCase();
}
});

result.should.eql([
'<a class="archive-link" href="/archives/2014/02/">FEBRUARY 2014<span class="archive-count">1</span></a>',
'<a class="archive-link" href="/archives/2013/10/">OCTOBER 2013<span class="archive-count">1</span></a>',
'<a class="archive-link" href="/archives/2013/06/">JUNE 2013<span class="archive-count">2</span></a>'
].join(', '));
});

it('separator', () => {
const result = listArchives({
style: false,
Expand Down

0 comments on commit cdea2aa

Please sign in to comment.