Convert seconds to compound duration: Difference between revisions

Content deleted Content added
Chkas (talk | contribs)
Hout (talk | contribs)
m →‎JS :: ES6: (tidying)
Line 1,948: Line 1,948:


====ES6====
====ES6====
<lang JavaScript>(() => {

<lang JavaScript>((localNames) => {
const main = () => {
const localNames = ['wk', 'd', 'hr', 'min', 'sec'];
return [7259, 86400, 6E6]
.map(intSeconds =>
`${intSeconds} -> ${
compoundDuration(localNames)(intSeconds)
}`)
.join('\n');
};


// compoundDuration :: [String] -> Int -> String
// compoundDuration :: [String] -> Int -> String
const compoundDuration = (labels, intSeconds) =>
const compoundDuration = labels =>
weekParts(intSeconds)
intSeconds => weekParts(intSeconds)
.map((v, i) => [v, labels[i]])
.map((v, i) => [v, labels[i]])
.reduce((a, x) =>
.reduce((a, x) =>
a.concat(x[0] ? [`${x[0]} ${x[1] || '?'}`] : []), []
a.concat(x[0] ? ([
`${x[0]} ${x[1] || '?'}`
]) : []), []
)
)
.join(', '),
.join(', '),
Line 1,963: Line 1,973:
weekParts = intSeconds => [0, 7, 24, 60, 60]
weekParts = intSeconds => [0, 7, 24, 60, 60]
.reduceRight((a, x) => {
.reduceRight((a, x) => {
let r = a.rem,
const
r = a[0],
mod = x !== 0 ? r % x : r;
mod = x !== 0 ? r % x : r;
return Tuple((r - mod) / (x || 1))(
[mod].concat(a[1])
);
}, Tuple(intSeconds)([]))[1]


return {
rem: (r - mod) / (x || 1),
parts: [mod].concat(a.parts)
};
}, {
rem: intSeconds,
parts: []
})
.parts;


// TEST
return [7259, 86400, 6E6]
.map(intSeconds =>
`${intSeconds} -> ${compoundDuration(localNames, intSeconds)}`
)
.join("\n");


// ---------------------- GENERIC ----------------------
})(["wk", "d", "hr", "min", "sec"]);</lang>
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});


// ---
return main();
})();</lang>
{{Out}}
{{Out}}
<pre>7259 -> 2 hr, 59 sec
<pre>7259 -> 2 hr, 59 sec