【发布时间】:2019-11-01 17:03:07
【问题描述】:
我尝试重写 compose 函数以使用不同的参数打印到控制台,但我仍然无法弄清楚。第一次调用 compose 函数 arg 是未定义的。因此,reduce 函数将使用数组的第一个元素 (console.clear()) 作为初始值,并将其用作下一个函数 getCurrentTime 的参数。
当使用 convertToCivilianTime 调用 compose 时,它使用来自 serializeClockTime 的返回值作为 compose 中第一个返回函数的参数。
那么,第一次使用未定义的arg 参数调用 compose 时如何不会导致错误?
const compose = (...fns) =>
(arg) =>
fns.reduce( (composed, f) => f(composed), arg)
const oneSecond = () => 1000
const getCurrentTime = () => new Date()
const clear = () => console.clear()
const log = message => console.log(message)
const serializeClockTime = date => ({
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds()
})
const civilianHours = clockTime => ({
...clockTime,
hours: ( clockTime.hours > 12 ) ? clockTime.hours - 12 : clockTime.hours
})
const appendAMPM = clockTime => ({
...clockTime,
ampm: ( clockTime.hours >= 12 ) ? "PM" : "AM"
})
const display = target => time => target(time)
const formatClock = format => time => format.replace('hh', time.hours).replace('mm', time.minutes).replace('ss', time.seconds).replace('tt', time.ampm)
const prependZero = key => clockTime => ({
...clockTime,
[key] : ( clockTime[key] < 10 ) ? "0" + clockTime[key] : clockTime[key]
})
const convertToCivilianTime = clockTime => compose(appendAMPM, civilianHours)(clockTime)
const doubleDigits = civilianTime => compose(
prependZero('hours'),
prependZero('minutes'),
prependZero('seconds')
)(civilianTime)
const startTicking = () => setInterval(compose(
clear,
getCurrentTime,
serializeClockTime,
convertToCivilianTime,
doubleDigits,
formatClock('hh:mm:ss tt'),
display(log)
),
oneSecond()
)
startTicking()
【问题讨论】:
-
你遇到了什么错误?
-
我没有收到错误,我想知道为什么在首次调用 compose 时未定义 arg 时没有错误。
标签: javascript