【问题标题】:Is there a way to parameterise the right hand side of a filter evaluation in a curried function有没有办法在柯里化函数中参数化过滤器评估的右侧
【发布时间】:2020-07-27 12:55:58
【问题描述】:

我想转换以下内容以使其可重用/通用。具体来说,我不确定采用什么方法来参数化过滤器评估的右侧。

这是我目前所拥有的,适用于以下用例。我正在尝试将咖喱部分转换为这样的东西......

const filterProcess = theFilter => theData => theFilter === ${dataBranch}.${dataLeaf}

我当前的工作用例。

const hotelList = [
    {city: "London", hotel: 1},
    {city: "Prague", hotel: 1},
    {city: "London", hotel: 2},
    {city: "Prague", hotel: 2},
]

const isLocated = location => hotels => location === hotels.city

const hotelsIn = hotelList.filter(isLocated(location));

console.log(hotelsIn('London'))

【问题讨论】:

    标签: javascript functional-programming currying


    【解决方案1】:

    采用迭代方法,由于hotelsIn 需要是一个函数,因此您希望isLocated 返回一个接受位置的函数:

    const hotelList = [
        {city: "London", hotel: 1},
        {city: "Prague", hotel: 1},
        {city: "London", hotel: 2},
        {city: "Prague", hotel: 2},
    ]
    
    const isLocated = location => hotel => location === hotel.city
    
    const hotelsIn = location => hotelList.filter(isLocated(location));
    // −−−−−−−−−−−−−−^^^^^^^^^^^^
    
    console.log(hotelsIn('London'))

    然后我们可以通过分解属性名称 (city) 来概括这一点:

    const hotelList = [
        {city: "London", hotel: 1},
        {city: "Prague", hotel: 1},
        {city: "London", hotel: 2},
        {city: "Prague", hotel: 2},
    ]
    
    const isLocated = (name, value) => item => value === item[name]
    // −−−−−−−−−−−−−−−^^^^^       ^    ^^^^    ^^^^^     ^^^^^^^^^^
    
    const hotelsIn = (name, location) => hotelList.filter(isLocated(name, location))
    // −−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^
    
    console.log(hotelsIn('city', 'London'))
    // −−−−−−−−−−−−−−−−−−^^^^^^^

    如果您愿意,可以添加 hotelsInCity 函数:

    const hotelList = [
        {city: "London", hotel: 1},
        {city: "Prague", hotel: 1},
        {city: "London", hotel: 2},
        {city: "Prague", hotel: 2},
    ]
    
    const isLocated = (name, value) => item => value === item[name]
    
    const hotelsIn = (name, location) => hotelList.filter(isLocated(name, location))
    
    const hotelsInCity = city => hotelsIn('city', city)
    
    console.log(hotelsInCity('London'))

    【讨论】:

    • 嗨,T.J,非常感谢。这有效并且有意义。我不是专业的开发人员,但我会尽量适应它。感谢您快速简洁的回答。
    • 为什么不把那个函数也加起来呢? const hasProperty = name => value => obj => value === obj[name]; const isLocated = hasProperty('city'); const inLondon = isLocated('London');
    • @Bergi - 嘿,是的,我也这样做了,就像hotelsInCity。您可以随意混合和旋转它。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2014-12-30
    • 2019-06-02
    • 2011-06-25
    • 1970-01-01
    相关资源
    最近更新 更多