speed up getAdjacentEl (#726)

* use element accessors

* don't change params
This commit is contained in:
Konstantin Vyatkin 2019-10-31 13:49:27 -04:00 committed by Josh Johnson
parent 9e11db8181
commit 5afe8b5a7f

View file

@ -1,16 +1,8 @@
export const getRandomNumber = (min, max) => export const getRandomNumber = (min, max) =>
Math.floor(Math.random() * (max - min) + min); Math.floor(Math.random() * (max - min) + min);
export const generateChars = length => { export const generateChars = length =>
let chars = ''; Array.from({ length }, () => getRandomNumber(0, 36).toString(36)).join('');
for (let i = 0; i < length; i++) {
const randomChar = getRandomNumber(0, 36);
chars += randomChar.toString(36);
}
return chars;
};
export const generateId = (element, prefix) => { export const generateId = (element, prefix) => {
let id = let id =
@ -44,19 +36,30 @@ export const wrap = (element, wrapper = document.createElement('div')) => {
*/ */
export const findAncestorByAttrName = (el, attr) => el.closest(`[${attr}]`); export const findAncestorByAttrName = (el, attr) => el.closest(`[${attr}]`);
export const getAdjacentEl = (startEl, className, direction = 1) => { export const getAdjacentEl =
if (!startEl || !className) { /**
return; * @param {Element} startEl
* @param {string} selector
* @param {1 | -1} direction
* @returns {Element | undefined}
*/
(startEl, selector, direction = 1) => {
if (!(startEl instanceof Element) || typeof selector !== 'string') {
return undefined;
} }
const parent = startEl.parentNode.parentNode; const prop = `${direction > 0 ? 'next' : 'previous'}ElementSibling`;
const children = Array.from(parent.querySelectorAll(className));
const startPos = children.indexOf(startEl); let sibling = startEl[prop];
const operatorDirection = direction > 0 ? 1 : -1; while (sibling) {
if (sibling.matches(selector)) {
return sibling;
}
sibling = sibling[prop];
}
return children[startPos + operatorDirection]; return sibling;
}; };
export const isScrolledIntoView = (el, parent, direction = 1) => { export const isScrolledIntoView = (el, parent, direction = 1) => {
if (!el) { if (!el) {