1 const conversions = require('./conversions');
4 This function routes a model to all other models.
6 all functions that are routed have a property `.conversion` attached
7 to the returned synthetic function. This property is an array
8 of strings, each with the steps in between the 'from' and 'to'
9 color models (inclusive).
11 conversions that are not possible simply are not included.
14 function buildGraph() {
16 // https://jsperf.com/object-keys-vs-for-in-with-closure/3
17 const models = Object.keys(conversions);
19 for (let len = models.length, i = 0; i < len; i++) {
21 // http://jsperf.com/1-vs-infinity
22 // micro-opt, but this is simple.
31 // https://en.wikipedia.org/wiki/Breadth-first_search
32 function deriveBFS(fromModel) {
33 const graph = buildGraph();
34 const queue = [fromModel]; // Unshift -> queue -> pop
36 graph[fromModel].distance = 0;
38 while (queue.length) {
39 const current = queue.pop();
40 const adjacents = Object.keys(conversions[current]);
42 for (let len = adjacents.length, i = 0; i < len; i++) {
43 const adjacent = adjacents[i];
44 const node = graph[adjacent];
46 if (node.distance === -1) {
47 node.distance = graph[current].distance + 1;
48 node.parent = current;
49 queue.unshift(adjacent);
57 function link(from, to) {
58 return function (args) {
59 return to(from(args));
63 function wrapConversion(toModel, graph) {
64 const path = [graph[toModel].parent, toModel];
65 let fn = conversions[graph[toModel].parent][toModel];
67 let cur = graph[toModel].parent;
68 while (graph[cur].parent) {
69 path.unshift(graph[cur].parent);
70 fn = link(conversions[graph[cur].parent][cur], fn);
71 cur = graph[cur].parent;
78 module.exports = function (fromModel) {
79 const graph = deriveBFS(fromModel);
80 const conversion = {};
82 const models = Object.keys(graph);
83 for (let len = models.length, i = 0; i < len; i++) {
84 const toModel = models[i];
85 const node = graph[toModel];
87 if (node.parent === null) {
88 // No possible conversion, or this node is the source model.
92 conversion[toModel] = wrapConversion(toModel, graph);