forked from sindresorhus/srcset
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (62 loc) · 1.72 KB
/
index.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
'use strict';
const integerRegex = /^-?\d+$/;
function deepUnique(array) {
return array.sort().filter((element, index) => {
return JSON.stringify(element) !== JSON.stringify(array[index - 1]);
});
}
exports.parse = string => {
return deepUnique(
// support links in skincity
string.split(/,\s*/).map(part => {
const result = {};
part
.trim()
.split(/\s+/)
.forEach((element, index) => {
if (index === 0) {
result.url = element;
return;
}
const value = element.slice(0, -1);
const postfix = element[element.length - 1];
const integerValue = Number.parseInt(value, 10);
const floatValue = Number.parseFloat(value);
if (postfix === 'w' && integerRegex.test(value)) {
if (integerValue <= 0) {
throw new Error('Width descriptor must be greater than zero');
}
result.width = integerValue;
} else if (postfix === 'x' && !Number.isNaN(floatValue)) {
if (floatValue <= 0) {
throw new Error('Pixel density descriptor must be greater than zero');
}
result.density = floatValue;
} else {
throw new Error(`Invalid srcset descriptor: ${element}`);
}
if (result.width && result.density) {
throw new Error('Image candidate string cannot have both width descriptor and pixel density descriptor');
}
});
return result;
})
);
};
exports.stringify = array => {
return [...new Set(
array.map(element => {
if (!element.url) {
throw new Error('URL is required');
}
const result = [element.url];
if (element.width) {
result.push(`${element.width}w`);
}
if (element.density) {
result.push(`${element.density}x`);
}
return result.join(' ');
})
)].join(', ');
};