Skip to content

Commit

Permalink
refactor(locals): utilize hexo-util's Cache()
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Dec 20, 2019
1 parent 09316c2 commit c6e6e6b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
21 changes: 9 additions & 12 deletions lib/hexo/locals.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
'use strict';

const { Cache } = require('hexo-util');

class Locals {
constructor() {
this.cache = {};
this.cache = new Cache();
this.getters = {};
}

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

let cache = this.cache[name];

if (cache == null) {
return this.cache.apply(name, () => {
const getter = this.getters[name];
if (!getter) return;

cache = getter();
this.cache[name] = cache;
}

return cache;
return getter();
});
}

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

this.getters[name] = getter;
this.cache[name] = null;
this.cache.del(name);

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

this.getters[name] = null;
this.cache[name] = null;
this.cache.del(name);

return this;
}

invalidate() {
this.cache = {};
this.cache.flush();

return this;
}
Expand Down
8 changes: 4 additions & 4 deletions test/scripts/hexo/locals.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ describe('Locals', () => {
locals.set('foo', () => 'foo');

// cache should be clear after new data is set
should.not.exist(locals.cache.foo);
should.not.exist(locals.cache.cache.foo);
locals.get('foo').should.eql('foo');
// cache should be saved once it's get
locals.cache.foo.should.eql('foo');
locals.cache.cache.foo.should.eql('foo');
});

it('set() - not function', () => {
Expand Down Expand Up @@ -69,7 +69,7 @@ describe('Locals', () => {
locals.remove('foo');

should.not.exist(locals.getters.foo);
should.not.exist(locals.cache.foo);
should.not.exist(locals.cache.cache.foo);
});

it('remove() - name must be a string', () => {
Expand Down Expand Up @@ -100,6 +100,6 @@ describe('Locals', () => {
locals.get('foo');
locals.invalidate();

should.not.exist(locals.cache.foo);
should.not.exist(locals.cache.cache.foo);
});
});

0 comments on commit c6e6e6b

Please sign in to comment.