From cdea2aaf1b5bd905bd92e47375dc252aa24f837f Mon Sep 17 00:00:00 2001 From: dailyrandomphoto Date: Thu, 26 Dec 2019 14:29:01 +0800 Subject: [PATCH] refactor(list_archives): Reduce calls to date.format() --- lib/plugins/helper/list_archives.js | 10 +++++++--- test/scripts/helpers/list_archives.js | 28 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/lib/plugins/helper/list_archives.js b/lib/plugins/helper/list_archives.js index db6860663c..e57d1245b1 100644 --- a/lib/plugins/helper/list_archives.js +++ b/lib/plugins/helper/list_archives.js @@ -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) { @@ -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, diff --git a/test/scripts/helpers/list_archives.js b/test/scripts/helpers/list_archives.js index 6c94f71fc1..b2bbb4daec 100644 --- a/test/scripts/helpers/list_archives.js +++ b/test/scripts/helpers/list_archives.js @@ -93,6 +93,19 @@ describe('list_archives', () => { ].join('')); }); + it('show_count + style: false', () => { + const result = listArchives({ + style: false, + show_count: false + }); + + result.should.eql([ + 'February 2014', + 'October 2013', + 'June 2013' + ].join(', ')); + }); + it('order', () => { const result = listArchives({ order: 1 @@ -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([ + 'FEBRUARY 20141', + 'OCTOBER 20131', + 'JUNE 20132' + ].join(', ')); + }); + it('separator', () => { const result = listArchives({ style: false,