From a9f19588ce7b4265d8b3f540cc83c601ac284bd5 Mon Sep 17 00:00:00 2001 From: Sukka Date: Thu, 6 Aug 2020 13:14:58 +0800 Subject: [PATCH] refactor: use Object.assign & Map (#36) --- lib/pagination.js | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/lib/pagination.js b/lib/pagination.js index 7217427..8d6f07a 100644 --- a/lib/pagination.js +++ b/lib/pagination.js @@ -6,23 +6,26 @@ function pagination(base, posts, options = {}) { if (typeof base !== 'string') throw new TypeError('base must be a string!'); if (!posts) throw new TypeError('posts is required!'); - if (base && base[base.length - 1] !== '/') base += '/'; + if (base && !base.endsWith('/')) base += '/'; + + const { length } = posts; + + const { format: _format, layout, data, perPage } = Object.assign({ + format: 'page/%d/', + layout: ['archive', 'index'], + data: {}, + perPage: 10 + }, options); - const length = posts.length; - const perPage = Object.prototype.hasOwnProperty.call(options, 'perPage') ? +options.perPage : 10; const total = perPage ? Math.ceil(length / perPage) : 1; - const _format = options.format || 'page/%d/'; - const layout = options.layout || ['archive', 'index']; - const data = options.data || {}; const result = []; - const urlCache = {}; + const urlCache = new Map(); function formatURL(i) { - if (urlCache[i]) return urlCache[i]; + if (urlCache.has(i)) return urlCache.get(i); - let url = base; - if (i > 1) url += format(_format, i); - urlCache[i] = url; + const url = i > 1 ? base + format(_format, i) : base; + urlCache.set(i, url); return url; }