UNPKG

1.23 kBJavaScriptView Raw
1/**
2 * Creates a graph of supported format transforms
3 *
4 * @param {Array<string>} transforms An array of supported transformations
5 * with the shape `formatA_formatB`; where formatA is
6 * the source format and formatB the destination format
7 * @return {Object} A graph of supported transformations, e.g:
8 *
9 * ```
10 * {
11 * amd: { cjs: {} },
12 * cjs: { steal: {} },
13 * steal: {}
14 * }
15 * ```
16 *
17 * The graph above indicates that's possible to transform from `amd` to `cjs`,
18 * and from `cjs` to the `steal` format.
19 */
20module.exports = function(transforms) {
21 var graph = makeEmptyGraph();
22
23 transforms.forEach(function(transform) {
24 var parts = transform.split("_");
25
26 var source = parts[0];
27 var dest = parts[1];
28
29 graph[source] = graph[source] || makeEmptyGraph();
30 graph[dest] = graph[dest] || makeEmptyGraph();
31
32 if (source === dest) {
33 // Prevent duplicating `graph[source]` in `graph[source][dest]`
34 graph[source][dest] = makeEmptyGraph();
35 }
36 else {
37 // use a shallow clone of `graph[dest]` to avoid a recursive graph
38 graph[source][dest] = Object.assign({}, graph[dest]);
39 }
40 });
41
42 return graph;
43};
44
45function makeEmptyGraph() {
46 return Object.create(null);
47}