juggl/juggl-vue/src/services/helper.service.js
2021-01-01 16:35:35 +01:00

111 lines
2.9 KiB
JavaScript

/**
* Contains a bunch of helper functions.
*/
export const helperService = {
/**
* Converts number into a human readable percent integer.
*
* @param {*} r Floating point percent number
*/
asPercent(r) {
return Math.floor(r * 100);
},
/**
* Converts number into a human readable floating point number with a digit behind the delimiter.
*
* @param {*} r Floating point number
*/
asFloat(r) {
return Math.floor(r * 10) / 10;
},
/**
* Converts timestamp into a human readable date format.
*
* @param {*} d ISO Timestamp
*/
asDateFromISO(d) {
return helperService.asDateFromObj(new Date(d));
},
/**
* Converts timestamp into a human readable date format.
*
* @param {*} d Date object
*/
asDateFromObj(d) {
return new Intl.DateTimeFormat("de").format(d);
},
/**
* Makes sure, that the given text is not too long.
*
* @param {*} text Some text that might be shortened
* @param {*} maxLength Max number of characters
*
* @returns The shortened or same text
*/
keepItShort(text, maxLength = 20, ellipsis = "...") {
if (text.length > maxLength) {
// Adding ellipsis
var short = text.substring(0, maxLength - ellipsis.length).trim();
return short + ellipsis;
} else return text;
},
/**
* Converts a date object into a date-time-timezone string, and sets times and timezone to zero.
*
* @source https://stackoverflow.com/a/43528844/7376120
*
* @param {*} date A date object
*
* @returns Date as string in the used format
*/
toISODate(date) {
var timezoneOffset = date.getMinutes() + date.getTimezoneOffset();
var timestamp = date.getTime() + timezoneOffset * 1000;
var correctDate = new Date(timestamp);
correctDate.setUTCHours(0, 0, 0, 0);
return correctDate.toISOString();
},
/**
* Adds current duration to a record.
* Copied from original juggl code.
* @param {*} record The record instance to update.
*/
addDuration(record) {
if (record.end_time != null) return record;
record.duration =
(new Date().getTime() - new Date(record.start_time).getTime()) /
1000;
return record;
},
/**
* Converts a datetime object into the necessary string format for server requests.
* Copied from original juggl code.
* @param {*} date
*/
dateToString(date) {
return (
date.getFullYear() +
"-" +
(date.getMonth() + 1) +
"-" +
date.getDate() +
" " +
date.getHours() +
":" +
date.getMinutes() +
":" +
date.getSeconds()
);
},
};