Skip to content

Commit

Permalink
Simplify with many-keys-map (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored and sindresorhus committed Mar 20, 2019
1 parent 840f1e8 commit 1d76111
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 24 deletions.
35 changes: 11 additions & 24 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,43 @@
'use strict';
const PCancelable = require('p-cancelable');
const ManyKeysMap = require('many-keys-map');

const targetCache = new WeakMap();

const cleanCache = (target, selector) => {
const map = targetCache.get(target);
if (map) {
map.delete(selector);
if (map.size === 0) {
targetCache.delete(target);
}
}
};
const cache = new ManyKeysMap();

const elementReady = (selector, options) => {
options = Object.assign({
const {target} = Object.assign({
target: document
}, options);

if (targetCache.has(options.target) && targetCache.get(options.target).has(selector)) {
return targetCache.get(options.target).get(selector);
let promise = cache.get([target, selector]);
if (promise) {
return promise;
}

let alreadyFound = false;
const promise = new PCancelable((resolve, reject, onCancel) => {
promise = new PCancelable((resolve, reject, onCancel) => {
let rafId;
onCancel(() => {
cancelAnimationFrame(rafId);
cleanCache(options.target, selector);
cache.delete([target, selector], promise);
});

// Interval to keep checking for it to come into the DOM
(function check() {
const el = options.target.querySelector(selector);
const el = target.querySelector(selector);

if (el) {
resolve(el);
alreadyFound = true;
cleanCache(options.target, selector);
cache.delete([target, selector], promise);
} else {
rafId = requestAnimationFrame(check);
}
})();
});

// The element might have been found in the first synchronous check
if (!alreadyFound) {
if (targetCache.has(options.target)) {
targetCache.get(options.target).set(selector, promise);
} else {
targetCache.set(options.target, new Map([[selector, promise]]));
}
cache.set([target, selector], promise);
}

return promise;
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"check"
],
"dependencies": {
"many-keys-map": "^1.0.0",
"p-cancelable": "^1.1.0"
},
"devDependencies": {
Expand Down

0 comments on commit 1d76111

Please sign in to comment.