File: lib/serialize/csv.js
/*
* niViz -- snow profiles visualization
* Copyright (C) 2015 WSL/SLF - Fluelastrasse 11 - 7260 Davos Dorf - Switzerland.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* eslint no-loop-func: [0] */
(function (niviz) {
'use strict';
// --- Module Dependencies ---
/** @module niviz */
/**
* Serialize data into CSV format
*
* @class CSV
* @constructor
*/
var CSV = {};
// Extract all parameters currently displayed from a Meteograph object.
// Eliminate all duplicates (may occur when using grouped parameters).
function uniqueparams (data) {
var parameters = [];
// Get the parameters on display
data.parameters.forEach(function (parameter) {
data.curves.forEach(function (curve) {
if (curve.name === parameter) {
curve.parameters.forEach(function (p) {
if (parameters.indexOf(p) === -1) parameters.push(p);
});
}
});
});
return parameters;
}
// For all parameters in the parameters array extract all values
// in the currently displayed window of the Meteograph object.
function extract (data, parameters) {
var meteo = data.data.data, start = 0, end = meteo.length - 1, i, result = '';
if (data.$indices) {
start = data.$indices.start;
end = data.$indices.end;
}
for (i = start; i <= end; ++i) {
result += meteo[i].timestamp.format('YYYY-MM-DDTHH:mm:ss');
parameters.forEach(function (p) {
if (meteo[i][p]) {
result += ',' + meteo[i][p];
} else {
result += ',-999';
}
});
result += '\n';
}
return result;
}
/**
* Serialize Meteograph object
*
* @method serialize
* @static
*
* @param {Meteograph} data The input data.
*
* @returns {String} The serialized result.
*/
CSV.serialize = function (data) {
var result;
if (data.parameters) {
var parameters = uniqueparams(data);
result = 'date,' + parameters.join(',') + '\n'; // print header
result += extract(data, parameters); // print body
}
return result;
};
// --- Module Exports ---
niviz.CSV = CSV;
}(niviz));