Skip to content

Commit c6e6e6b

Browse files
committed
refactor(locals): utilize hexo-util's Cache()
1 parent 09316c2 commit c6e6e6b

File tree

2 files changed

+13
-16
lines changed

2 files changed

+13
-16
lines changed

lib/hexo/locals.js

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,22 @@
11
'use strict';
22

3+
const { Cache } = require('hexo-util');
4+
35
class Locals {
46
constructor() {
5-
this.cache = {};
7+
this.cache = new Cache();
68
this.getters = {};
79
}
810

911
get(name) {
1012
if (typeof name !== 'string') throw new TypeError('name must be a string!');
1113

12-
let cache = this.cache[name];
13-
14-
if (cache == null) {
14+
return this.cache.apply(name, () => {
1515
const getter = this.getters[name];
1616
if (!getter) return;
1717

18-
cache = getter();
19-
this.cache[name] = cache;
20-
}
21-
22-
return cache;
18+
return getter();
19+
});
2320
}
2421

2522
set(name, value) {
@@ -29,7 +26,7 @@ class Locals {
2926
const getter = typeof value === 'function' ? value : () => value;
3027

3128
this.getters[name] = getter;
32-
this.cache[name] = null;
29+
this.cache.del(name);
3330

3431
return this;
3532
}
@@ -38,13 +35,13 @@ class Locals {
3835
if (typeof name !== 'string') throw new TypeError('name must be a string!');
3936

4037
this.getters[name] = null;
41-
this.cache[name] = null;
38+
this.cache.del(name);
4239

4340
return this;
4441
}
4542

4643
invalidate() {
47-
this.cache = {};
44+
this.cache.flush();
4845

4946
return this;
5047
}

test/scripts/hexo/locals.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ describe('Locals', () => {
2424
locals.set('foo', () => 'foo');
2525

2626
// cache should be clear after new data is set
27-
should.not.exist(locals.cache.foo);
27+
should.not.exist(locals.cache.cache.foo);
2828
locals.get('foo').should.eql('foo');
2929
// cache should be saved once it's get
30-
locals.cache.foo.should.eql('foo');
30+
locals.cache.cache.foo.should.eql('foo');
3131
});
3232

3333
it('set() - not function', () => {
@@ -69,7 +69,7 @@ describe('Locals', () => {
6969
locals.remove('foo');
7070

7171
should.not.exist(locals.getters.foo);
72-
should.not.exist(locals.cache.foo);
72+
should.not.exist(locals.cache.cache.foo);
7373
});
7474

7575
it('remove() - name must be a string', () => {
@@ -100,6 +100,6 @@ describe('Locals', () => {
100100
locals.get('foo');
101101
locals.invalidate();
102102

103-
should.not.exist(locals.cache.foo);
103+
should.not.exist(locals.cache.cache.foo);
104104
});
105105
});

0 commit comments

Comments
 (0)