我正在使用多个选择器来获取设置 Google map 的边界。它们基本上返回数据中的最低和最高纬度/经度点。该代码可以工作,但我觉得这真的很困惑,可以重构,但我不太确定如何重构。
这是代码:
const getMinLat = data =>
data.reduce((prev, current) => {
return prev.coords[0] < current.coords[0] ? prev : current
})
const getMaxLat = data =>
data.reduce((prev, current) => {
return prev.coords[0] > current.coords[0] ? prev : current
})
const getMinLng = data =>
data.reduce((prev, current) => {
return prev.coords[1] < current.coords[1] ? prev : current
})
const getMaxLng = data =>
data.reduce((prev, current) => {
return prev.coords[1] > current.coords[1] ? prev : current
})
const getBounds = data => [
{
lat: getMinLat(data).coords[0],
lng: getMinLng(data).coords[1],
},
{
lat: getMaxLat(data).coords[0],
lng: getMaxLng(data).coords[1],
},
]
最佳答案
只需遍历列表一次:
const getBounds = data =>
data.reduce(
([
{lat: minLat, lng: minLng},
{lat: maxLat, lng: maxLng}
],
{coords: [lat, lng]}
) =>
[
{
lat: Math.min(minLat, lat),
lng: Math.min(minLng, lng)
},
{
lat: Math.max(maxLat, lat),
lng: Math.max(maxLng, lng)
}
],
[{lat: Infinity, lng: Infinity}, {lat: -Infinity, lng: -Infinity}]
)
我事先同意,可读性并不是这里的优势。但它只遍历列表一次。
此外,在习惯了解构语法之后,很明显,Math.max
和 maxLng/maxLat
结合在一起可以减少使用错误变量的可能性
[UPD]并且不需要使用Infinity/-Infinity
作为起始值(我用它们来突出背后的想法)。对于经度/纬度,我们可以使用 180/-180
作为最极端的值
关于javascript - react JS : Refactoring Redux Selectors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53447632/