forked from leeoniya/dropcss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nth.js
59 lines (44 loc) · 1.31 KB
/
nth.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
"use strict";
// adapted from https://github.com/fb55/nth-check/blob/master/compile.js
// https://css-tricks.com/how-nth-child-works/
// https://css-tricks.com/useful-nth-child-recipies/
// https://css-tricks.com/examples/nth-child-tester/
// http://nthmaster.com/
/* leon's incomplete attempt
function nthChild(el, a, b) {
if (a < 0) {
console.log("Unimplemented: -A in :nth-child(An+B)", m);
return true;
}
let p = el.idx + 1;
let diff = p - b;
return diff >= 0 && diff % a == 0;
}
*/
/*
tests if an element's pos (index+1) matches the given rule
highly optimized to return the fastest solution
*/
function nth(a, b, pos) {
//when b <= 0, a*n won't be possible for any matches when a < 0
//besides, the specification says that no element is matched when a and b are 0
if (b < 0 && a <= 0)
return false;
//when a is in the range -1..1, it matches any element (so only b is checked)
if (a === -1)
return pos <= b;
if (a === 0)
return pos === b;
//when b <= 0 and a === 1, they match any element
if (a === 1)
return b < 0 || pos >= b;
//when a > 0, modulo can be used to check if there is a match
let bMod = b % a;
if (bMod < 0)
bMod += a;
if (a > 1)
return pos >= b && pos % a === bMod;
a *= -1; //make `a` positive
return pos <= b && pos % a === bMod;
}
exports.nth = nth;