Skip to content

Commit 1d76111

Browse files
fregantesindresorhus
authored andcommitted
Simplify with many-keys-map (#16)
1 parent 840f1e8 commit 1d76111

2 files changed

Lines changed: 12 additions & 24 deletions

File tree

index.js

Lines changed: 11 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,43 @@
11
'use strict';
22
const PCancelable = require('p-cancelable');
3+
const ManyKeysMap = require('many-keys-map');
34

4-
const targetCache = new WeakMap();
5-
6-
const cleanCache = (target, selector) => {
7-
const map = targetCache.get(target);
8-
if (map) {
9-
map.delete(selector);
10-
if (map.size === 0) {
11-
targetCache.delete(target);
12-
}
13-
}
14-
};
5+
const cache = new ManyKeysMap();
156

167
const elementReady = (selector, options) => {
17-
options = Object.assign({
8+
const {target} = Object.assign({
189
target: document
1910
}, options);
2011

21-
if (targetCache.has(options.target) && targetCache.get(options.target).has(selector)) {
22-
return targetCache.get(options.target).get(selector);
12+
let promise = cache.get([target, selector]);
13+
if (promise) {
14+
return promise;
2315
}
2416

2517
let alreadyFound = false;
26-
const promise = new PCancelable((resolve, reject, onCancel) => {
18+
promise = new PCancelable((resolve, reject, onCancel) => {
2719
let rafId;
2820
onCancel(() => {
2921
cancelAnimationFrame(rafId);
30-
cleanCache(options.target, selector);
22+
cache.delete([target, selector], promise);
3123
});
3224

3325
// Interval to keep checking for it to come into the DOM
3426
(function check() {
35-
const el = options.target.querySelector(selector);
27+
const el = target.querySelector(selector);
3628

3729
if (el) {
3830
resolve(el);
3931
alreadyFound = true;
40-
cleanCache(options.target, selector);
32+
cache.delete([target, selector], promise);
4133
} else {
4234
rafId = requestAnimationFrame(check);
4335
}
4436
})();
4537
});
4638

47-
// The element might have been found in the first synchronous check
4839
if (!alreadyFound) {
49-
if (targetCache.has(options.target)) {
50-
targetCache.get(options.target).set(selector, promise);
51-
} else {
52-
targetCache.set(options.target, new Map([[selector, promise]]));
53-
}
40+
cache.set([target, selector], promise);
5441
}
5542

5643
return promise;

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"check"
3333
],
3434
"dependencies": {
35+
"many-keys-map": "^1.0.0",
3536
"p-cancelable": "^1.1.0"
3637
},
3738
"devDependencies": {

0 commit comments

Comments
 (0)