material-duration-picker
Version:
React Material component for durations inspired by Material-UI Pickers
88 lines (87 loc) • 2.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.durationToTime = exports.timeToDuration = exports.getRemainder = exports.getValue = void 0;
var constants_1 = require("./constants");
/**
* Converts a number of seconds into a whole number of units of type view
*
* Ex:
* 75 seconds to minutes = 1.25 minutes. Rounded down = 1 minutes
*
* This works with negative numbers
* -75 seconds to minutes = -1.25 minutes. Rounded up = -1 minutes
*
* @param secs The number of seconds
* @param view The view
* @param round if should round
*/
var getValue = function (secs, view, round) {
if (round === void 0) { round = true; }
if (secs == null) {
return undefined;
}
/*
The bitwise operator is used to get the whole number.
https://stackoverflow.com/a/4228528/6592293
*/
var res = secs * constants_1.converters['seconds'][view];
return round ? res | 0 : res;
};
exports.getValue = getValue;
var getRemainder = function (secs, view) {
return secs == null ? undefined : secs % constants_1.converters[view]['seconds'];
};
exports.getRemainder = getRemainder;
/**
* Converts a time in seconds to a duration
* @param time time in seconds
* @param views Views included in the duration
* @param zeroes If false, views that have a value of zero will be set to undefined
*/
var timeToDuration = function (time, views, zeroes) {
if (views === void 0) { views = constants_1.VIEWS; }
if (zeroes === void 0) { zeroes = false; }
var i = 0;
var view = views[i];
if (!view || time == null) {
return {};
}
return constants_1.VIEWS.reduce(function (acc, curr) {
var value = exports.getValue(time, curr, curr !== 'seconds');
var remainder = exports.getRemainder(time, curr);
var a = value != null ? value * constants_1.converters[curr][view] : 0;
time = remainder !== null && remainder !== void 0 ? remainder : undefined;
acc[view] = ((acc[view] || 0) + a) || (zeroes ? 0 : undefined);
if (view === curr && i + 1 < views.length) {
i++;
view = views[i];
}
return acc;
}, {});
};
exports.timeToDuration = timeToDuration;
/**
* Convert a duration to a time value of a view
* If no view is specified, will convert to seconds
*
* Ex:
* duration: {
* hours: 1,
* minutes: 2
* seconds: 30
* }
* view: minutes
*
* res: 62.5
*/
var durationToTime = function (duration, view) {
var seconds = constants_1.VIEWS.reduce(function (time, view) {
var v = duration[view];
if (v == null) {
return time;
}
return (time !== null && time !== void 0 ? time : 0) + v * constants_1.toSecondsMultipliers[view];
}, undefined);
return view && seconds != null ? seconds / constants_1.toSecondsMultipliers[view] : seconds;
};
exports.durationToTime = durationToTime;