【问题标题】:Using lodash's fp functions in a flow在流中使用 lodash 的 fp 函数
【发布时间】:2018-07-10 09:48:19
【问题描述】:

读到_.chain 方法是“considered harmful”,我想我应该尝试一些流程。但是,我在使用 fp 方法时遇到了问题。

我在a repl 中添加了一个小示例,并复制了下面的代码。

const flow = require('lodash/fp/flow');
const truncate = require('lodash/fp/truncate');
const mapValues = require('lodash/fp/mapValues');
const { inspect, format } = require('util');

const input = {
    firstField: 'I am a fairly long string so I want to be truncated',
    secondField: {
        foo: 'bar',
        bar: 'baz',
        baz: 'boo',
        boo: 'hoo',
        hoo: 'boy',
        boy: 'howdy'
    }
};

const doTheThing = data =>
    flow(
        mapValues(inspect), 
        mapValues(s => s.replace(/\s*\n\s*/g, ' ')),
        mapValues(truncate)
    )(data);

console.log(doTheThing(input));

当我运行它时,truncate 并没有像我期望的那样被调用,对于输出我得到 ​​p>

{ firstField: { [Function: wrapper] placeholder: {} },
  secondField: { [Function: wrapper] placeholder: {} } }

我希望得到两个截断的字符串,而不是被 toString 处理过的函数。为此,我必须将其更改为 mapValues(s => truncate(s)(s))。至少可以说这看起来是错误的,所以我错误地结合了 flow 和 fp 方法,还是我使用错误?

【问题讨论】:

    标签: javascript functional-programming lodash


    【解决方案1】:

    你用错了。首先,对于普通的 Lodash,truncate 函数有两个参数:

    _.truncate([string=''], [options={}])

    第二个在哪里:

    [options={}](对象):选项对象。

    使用 Lodash fp there are no optional argumentssome functions' arguments are rearranged 使合成更容易。所以在 fp 中truncate 有两个参数,第一个是options 对象。要使用 fp 截断字符串,您需要提供两个参数:

    const truncFn = _.truncate({ length: 20 }); // is a function
    const truncatedString = truncFn('I am a fairly long string so I want to be truncated'); // only this results in truncated string
    
    console.log(truncatedString);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.fp.min.js"></script>

    您的 sn-p,固定版本 (repl link):

    const flow = require('lodash/fp/flow');
    const truncate = require('lodash/fp/truncate');
    const mapValues = require('lodash/fp/mapValues');
    const { inspect, format } = require('util');
    
    const input = {
        firstField: 'I am a fairly long string so I want to be truncated',
        secondField: {
            foo: 'bar',
            bar: 'baz',
            baz: 'boo',
            boo: 'hoo',
            hoo: 'boy',
            boy: 'howdy'
        }
    };
    
    const doTheThing = data =>
        flow(
            mapValues(inspect), 
            mapValues(s => s.replace(/\s*\n\s*/g, ' ')),
            mapValues(truncate({})) // <--- FIX
        )(data);
    
    console.log(doTheThing(input));
    

    【讨论】:

    • 太棒了,非常感谢您的详细回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2022-01-25
    相关资源
    最近更新 更多