This repository has been archived by the owner on Mar 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.js
78 lines (54 loc) · 2.22 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict'; // filter function for ancestor elements
var filterAncestor = function filterAncestor(item) {
return item.nodeType === 1 && item.tagName.toLowerCase() !== 'body' && item.tagName.toLowerCase() !== 'html';
}; // filter function for sibling elements
var filterSibling = function filterSibling(item) {
return item.nodeType === 1 && item.tagName.toLowerCase() !== 'script';
}; // reducer to flatten arrays
var flattenArrays = function flattenArrays(a, b) {
return a.concat(b);
}; // recursive function to get previous sibling nodes of given element
function getPreviousSiblings(el) {
var siblings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var previousSibling = el.previousSibling;
if (!previousSibling) {
return siblings;
}
siblings.push(previousSibling);
return getPreviousSiblings(previousSibling, siblings);
} // recursive function to get next sibling nodes of given element
function getNextSiblings(el) {
var siblings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var nextSibling = el.nextSibling;
if (!nextSibling) {
return siblings;
}
siblings.push(nextSibling);
return getNextSiblings(nextSibling, siblings);
} // returns all sibling element nodes of given element
function getSiblings(el) {
var allSiblings = getPreviousSiblings(el).concat(getNextSiblings(el));
return allSiblings.filter(filterSibling);
} // recursive function to get all ancestor nodes of given element
function getAllAncestors(el) {
var ancestors = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var nextAncestor = el.parentNode;
if (!nextAncestor) {
return ancestors;
}
ancestors.push(nextAncestor);
return getAllAncestors(nextAncestor, ancestors);
} // get ancestor nodes of given element
function getAncestors(el) {
return getAllAncestors(el).filter(filterAncestor);
} // get siblings of ancestors (i.e. aunts and uncles) of given el
function getSiblingsOfAncestors(el) {
return getAncestors(el).map(function (item) {
return getSiblings(item);
}).reduce(flattenArrays, []);
}
module.exports = {
getSiblings: getSiblings,
getAncestors: getAncestors,
getSiblingsOfAncestors: getSiblingsOfAncestors
};