debian-mirror-gitlab/app/assets/javascripts/analytics/usage_trends/utils.js

69 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-01-03 14:25:43 +05:30
import { masks } from 'dateformat';
2021-01-29 00:20:46 +05:30
import { get } from 'lodash';
2021-01-03 14:25:43 +05:30
import { formatDate } from '~/lib/utils/datetime_utility';
const { isoDate } = masks;
/**
* Takes an array of items and returns one item per month with the average of the `count`s from that month
* @param {Array} items
* @param {Number} items[index].count value to be averaged
* @param {String} items[index].recordedAt item dateTime time stamp to be collected into a month
* @param {Object} options
* @param {Object} options.shouldRound an option to specify whether the retuned averages should be rounded
* @return {Array} items collected into [month, average],
* where month is a dateTime string representing the first of the given month
* and average is the average of the count
*/
export function getAverageByMonth(items = [], options = {}) {
const { shouldRound = false } = options;
const itemsMap = items.reduce((memo, item) => {
const { count, recordedAt } = item;
const date = new Date(recordedAt);
const month = formatDate(new Date(date.getFullYear(), date.getMonth(), 1), isoDate);
if (memo[month]) {
const { sum, recordCount } = memo[month];
return { ...memo, [month]: { sum: sum + count, recordCount: recordCount + 1 } };
}
return { ...memo, [month]: { sum: count, recordCount: 1 } };
}, {});
2021-03-08 18:12:59 +05:30
return Object.keys(itemsMap).map((month) => {
2021-01-03 14:25:43 +05:30
const { sum, recordCount } = itemsMap[month];
const avg = sum / recordCount;
if (shouldRound) {
return [month, Math.round(avg)];
}
return [month, avg];
});
}
/**
2021-04-17 20:07:23 +05:30
* Takes an array of usage counts and returns the last item in the list
* @param {Array} arr array of usage counts in the form { count: Number, recordedAt: date String }
2021-01-29 00:20:46 +05:30
* @return {String} the 'recordedAt' value of the earliest item
2021-01-03 14:25:43 +05:30
*/
2021-01-29 00:20:46 +05:30
export const getEarliestDate = (arr = []) => {
const len = arr.length;
return get(arr, `[${len - 1}].recordedAt`, null);
};
2021-01-03 14:25:43 +05:30
/**
2021-01-29 00:20:46 +05:30
* Takes an array of queries and produces an object with the query identifier as key
* and a supplied defaultValue as its value
* @param {Array} queries array of chart query configs,
2021-04-17 20:07:23 +05:30
* see ./analytics/usage_trends/components/charts_config.js
2021-01-29 00:20:46 +05:30
* @param {any} defaultValue value to set each identifier to
* @return {Object} key value pair of the form { queryIdentifier: defaultValue }
2021-01-03 14:25:43 +05:30
*/
2021-01-29 00:20:46 +05:30
export const generateDataKeys = (queries, defaultValue) =>
queries.reduce(
(acc, { identifier }) => ({
...acc,
[identifier]: defaultValue,
}),
{},
);