Convert seconds to compound duration: Difference between revisions

Content added Content deleted
m (Changed header from 'freebasic' to 'FreeBASIC' as previously this task was listed as 'not implemented' in this language)
(→‎JS ES6: Slightly less parochial assumptions about local labels)
Line 1,372: Line 1,372:
====ES6====
====ES6====


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


// angloDuration :: Int -> String
// compoundDuration :: [String] -> Int -> String
let angloDuration = intSeconds =>
const compoundDuration = (labels, intSeconds) =>
weekParts(intSeconds)
weekParts(intSeconds)
.map((v, i) => [v, ["wk", "d", "hr", "min", "sec"][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(', '),


// weekParts :: Int -> [Int]
// weekParts :: Int -> [Int]
weekParts = intSeconds => [undefined, 7, 24, 60, 60]
weekParts = intSeconds => [0, 7, 24, 60, 60]
.reduceRight((a, x) => {
.reduceRight((a, x) => {
let r = a.rem,
let r = a.rem,
mod = isNaN(x) ? r : r % x;
mod = x !== 0 ? r % x : r;

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




Line 1,403: Line 1,403:
return [7259, 86400, 6E6]
return [7259, 86400, 6E6]
.map(intSeconds =>
.map(intSeconds =>
`${intSeconds} -> ${angloDuration(intSeconds)}`
`${intSeconds} -> ${compoundDuration(localNames, intSeconds)}`
)
)
.join("\n");
.join("\n");


})();</lang>
})(["wk", "d", "hr", "min", "sec"]);</lang>



{{Out}}
{{Out}}