Skip to content

Commit

Permalink
feat: add memoize function
Browse files Browse the repository at this point in the history
  • Loading branch information
yungo1846 committed Feb 28, 2021
1 parent 91f448c commit c679b6f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/js/util/DOM.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* eslint-disable max-lines-per-function */
import { memoize } from './index.js';

export const $ = (() => {
const constructor = function (selector) {
Expand All @@ -9,6 +9,10 @@ export const $ = (() => {
this.target = this.targets.length === 1 && this.targets[0];
};

const makeNewConstructor = function (selector) {
return new constructor(selector);
};

constructor.prototype.each = function (callBack) {
if (!callBack || typeof callBack !== 'function') {
throw new Error('Custom DOM Library Error: this method needs callback function!');
Expand Down Expand Up @@ -129,8 +133,10 @@ export const $ = (() => {
return this.target.checked;
};

const memoized = memoize(makeNewConstructor);

const instantiate = selector => {
return new constructor(selector);
return memoized(selector);
};

return instantiate;
Expand Down
1 change: 1 addition & 0 deletions src/js/util/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { $ } from './DOM.js';
export { validator } from './validator.js';
export { getRandomNumber } from './getRandomNumber.js';
export { memoize } from './memoize.js';
11 changes: 11 additions & 0 deletions src/js/util/memoize.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function memoize(callback) {
const cache = new Map();

return function (...args) {
if (!cache.get(args)) {
cache.set(args, new callback(args));
}

return cache.get(args);
};
}

0 comments on commit c679b6f

Please sign in to comment.