-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
Copy pathfilter-source.js
70 lines (61 loc) · 1.57 KB
/
filter-source.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
/**
* @module filter-source
*/
import {isObject} from './obj';
import {getMimetype} from './mimetypes';
/**
* Filter out single bad source objects or multiple source objects in an
* array. Also flattens nested source object arrays into a 1 dimensional
* array of source objects.
*
* @param {Tech~SourceObject|Tech~SourceObject[]} src
* The src object to filter
*
* @return {Tech~SourceObject[]}
* An array of sourceobjects containing only valid sources
*
* @private
*/
const filterSource = function(src) {
// traverse array
if (Array.isArray(src)) {
let newsrc = [];
src.forEach(function(srcobj) {
srcobj = filterSource(srcobj);
if (Array.isArray(srcobj)) {
newsrc = newsrc.concat(srcobj);
} else if (isObject(srcobj)) {
newsrc.push(srcobj);
}
});
src = newsrc;
} else if (typeof src === 'string' && src.trim()) {
// convert string into object
src = [fixSource({src})];
} else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
// src is already valid
src = [fixSource(src)];
} else {
// invalid source, turn it into an empty array
src = [];
}
return src;
};
/**
* Checks src mimetype, adding it when possible
*
* @param {Tech~SourceObject} src
* The src object to check
* @return {Tech~SourceObject}
* src Object with known type
*/
function fixSource(src) {
if (!src.type) {
const mimetype = getMimetype(src.src);
if (mimetype) {
src.type = mimetype;
}
}
return src;
}
export default filterSource;