apisearch-events-ui
Version:
Javascript User Interface to visualize all events data.
116 lines (106 loc) • 2.65 kB
JavaScript
import moment from "moment";
/**
* Check if a value is defined
*
* @param value
* @returns {boolean}
*/
export const isDefined = function(value) {
return typeof value !== 'undefined';
};
/**
* Get chart labels
*
* Returns an array of the chart labels
* every chart label is a moment instance.
*
* It takes as a starting point --> (now)
* and loops over every day until the totalDays value.
*
* @param start
* @param totalDays
* @returns {Array.<*>}
*/
export const getChartLabels = function(start, totalDays) {
let day = start.clone();
let days = [day];
for (let i = 0; i < totalDays; i++) {
day = day.clone().subtract(1, 'day');
days.push(day)
}
return days.reverse();
};
/**
* Format labels array
* given a Datetime format mask
*
* @param labels Array[Moment]
* @param format String
*/
export const composeLabels = function(labels, format) {
return labels.map(label => label.format(format))
};
/**
* Get label corresponding value
*
* Giving a label ("a unix datetime")
* and given "n" values with ("unix datetime" and "value")
* return the corresponding value that matches with the label datetime.
*
* @param label
* @param values
* @returns {number}
*/
function getLabelCorrespondingValue(label, values) {
let value = 0;
values.every(item => {
if (
moment
.unix(item.values.name)
.isSame(label, 'day')
) {
value = item.n;
return false;
}
return true;
});
return value;
}
/**
* Format data
*
* Formats the data to fill the chart spec.
*
* Takes the values received from the server
* and the current labels of the chart (the days)
*
* The sets the value received per each day on the data array.
* When there is no data of one day,
* by default the is set to "0". To be consistent with the chart labels.
*
* @param labels
* @param datasets
*/
export const composeDatasets = (labels, datasets) => {
return datasets.map(dataset => {
if (
typeof dataset.data === 'undefined' ||
typeof dataset.data.occurred_on_day === 'undefined'
) {
/**
* Return an array with 0 values for all the labels
*/
return {
...dataset,
data: labels.map(label => 0)
};
}
let values = dataset.data.occurred_on_day.counters;
return {
...dataset,
data: labels.map(label => {
return getLabelCorrespondingValue(label, values)
})
}
})
};