gradient-parser/lib/stringify.js
Rafael Caricio 129101533e Stringify
2014-09-19 19:40:56 +02:00

63 lines
1.4 KiB
JavaScript

// Copyright (c) 2014 Rafael Caricio. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var GradientParser = (GradientParser || {});
GradientParser.stringify = (function() {
var visitor = {
'visit_linear-gradient': function(node) {
var orientation = visitor.visit(node.orientation);
if (orientation) {
orientation += ', ';
}
return 'linear-gradient('+ orientation + visitor.visit(node.colorStops) + ')';
},
visit_literal: function(node) {
return node.value;
},
visit_array: function(elements) {
var result = '',
size = elements.length;
elements.forEach(function(element, i) {
result += visitor.visit(element);
if (i < size - 1) {
result += ', ';
}
});
return result;
},
visit: function(element) {
if (!element) {
return '';
}
if (element instanceof Array) {
return visitor.visit_array(element, result);
} else if (element.type) {
var nodeVisitor = visitor['visit_' + element.type];
if (nodeVisitor) {
return nodeVisitor(element);
} else {
throw Error('Missing visitor visit_' + element.type);
}
} else {
throw Error('Invalid node.');
}
}
};
return function(root) {
return visitor.visit(root);
};
})();