2 回答
TA贡献2019条经验 获得超9个赞
您也可以使用 vanilla JS 相对简单地完成此操作。这是一个版本:
const hoursToTimeStops = businessOpenSlots =>
Object .fromEntries (
Object .entries (businessOpenSlots) .map (([d, h]) => [d, h .flatMap (vm .getTimeStops)])
)
const businessOpenSlots = {monday: [{open: "0800", close: "1530"}, {open: "1730", close: "1930"}], tuesday: [{open: "24hrs", close: "24hrs"}], wednesday: [{open: "0900", close: "1700"}], thursday: [{open: "0900", close: "1700"}], friday: [{open: "0900", close: "1700"}]}
console .log (hoursToTimeStops (businessOpenSlots))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script> // Dummy implementation for `vm`.
const every15mins = (sh, sm, eh, em) => sh * 60 + sm > eh * 60 + em ? [] : [`${String(sh).padStart(2, '0')}:${String(sm).padStart(2, '0')}`, ...every15mins(sh + (sm >= 45 ? 1 : 0), (sm + 15) % 60, eh, em)]
const vm = {getTimeStops: ({open, close}) => open === '24hrs' ? ["00:00"] : every15mins(Number(open.slice(0, 2)), Number(open.slice(2, 4)), Number(close.slice(0, 2)), Number(close.slice(2, 4)))}
</script>
lodash (或 Ramda 的)很好地封装了调用entries
、map
ping 结果、然后调用的过程,但其余部分似乎比您的 lodash 版本更简单。fromEntries
mapValues
map
但是,我相信您应该能够大大简化该版本。我对 Ramda 更熟悉(免责声明:我是它的作者之一),而且我知道在 Ramda 中,我们可以简单地写:
const hoursToTimeStops = map (chain (vm.getTimeStops))
我猜你可以用 lodash 代替mapValues
和map
itsflatMap
代替chain
. (除非你使用 Lodash FP,否则它可能不会那么优雅,但也不会差那么远。)
TA贡献1847条经验 获得超7个赞
自己找到解决方案并在此处发布以供社区使用。
我只需要使用_.mapValues()Lodash。
let availableSlots = _.mapValues(businessOpenSlots, function(slots, weekday) {
return _.spread(_.union)(_.map(slots, slot => {
return vm.getTimeStops(slot.open, slot.close);
}))
});
log(availableSlots)
它返回以下内容,正如我想要的那样。
添加回答
举报