Convert seconds to compound duration: Difference between revisions

Content added Content deleted
(→‎JS ES6: Tidied.)
Line 2,217: Line 2,217:
====ES6====
====ES6====
<lang JavaScript>(() => {
<lang JavaScript>(() => {
const main = () => {
"use strict";

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


// compoundDuration :: [String] -> Int -> String
// compoundDuration :: [String] -> Int -> String
const compoundDuration = labels =>
const compoundDuration = labels =>
intSeconds => weekParts(intSeconds)
nSeconds => weekParts(nSeconds)
.map((v, i) => [v, labels[i]])
.map((v, i) => [v, labels[i]])
.reduce((a, x) =>
.reduce((a, x) =>
a.concat(x[0] ? ([
a.concat(
`${x[0]} ${x[1] || '?'}`
x[0] ? [
]) : []), []
`${x[0]} ${x[1] || "?"}`
] : []
), []
)
)
.join(', '),
.join(", ");



// weekParts :: Int -> [Int]
weekParts = intSeconds => [0, 7, 24, 60, 60]
// weekParts :: Int -> [Int]
const weekParts = nSeconds => [0, 7, 24, 60, 60]
.reduceRight((a, x) => {
.reduceRight((a, x) => {
const
const
r = a[0],
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 [
(r - mod) / (x || 1),
[mod, ...a[1]]
];
}, [nSeconds, []])[1];


// ---------------------- GENERIC ----------------------
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});


// ---------------------- TEST -----------------------
// ---
// main :: IO ()
const main = () => {
const localNames = ["wk", "d", "hr", "min", "sec"];

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

// MAIN ---
return main();
return main();
})();</lang>
})();</lang>