使用lodash cond进行某些分支

时间:2019-07-16 20:23:52

标签: javascript lodash

我正在尝试使用lodash cond调用提供不同输入的不同函数。也许我误会了cond,但是我真的很喜欢干净的条件处理方法。

基本上,我有一个二维数据数组(网格)。标头一维标头数组和一维总计数组。用户可以选择向数据数组添加数据头和总计。总行可以在顶部或底部。

这变成了八个条件,如下所示:

const totalAbove = totalPosition >= 1;
const totalBelow = totalPosition <= -1;

const hasLabelsAndTotalsAbove = showLables && totalAbove;
const hasLabelsAndTotalsBelow = showLables && totalBelow;

const noLabelsAndTotalsAbove = !showLables && totalAbove;
const noLabelsAndTotalsBelow = !showLables && totalBelow;

const noTotalHasLabels = showLables && !hasTotalRow;
const noTotalNoLabels = !showLables && !hasTotalRow;

然后我想我可以做到这一点:

const getData = cond([
            [hasLabelsAndTotalsAbove, () => Array.prototype.concat([headers], [totalRow], ...matrixes)],
            [hasLabelsAndTotalsBelow, () => Array.prototype.concat([headers], ...matrixes, [totalRow])],
            [noLabelsAndTotalsAbove, () => Array.prototype.concat([totalRow], ...matrixes)],
            [noLabelsAndTotalsBelow, () => Array.prototype.concat(...matrixes, [totalRow]) ],
            [noTotalHasLabels, () => Array.prototype.concat([headers], ...matrixes) ],
            [noTotalNoLabels, () => matrixes ]
        ]);

data = getData();

上面应该通过按正确的顺序将三个数组组合成所需的形式。但是结果只是不确定的。我完全误解了行为吗?

目前,我只是将_cond部分转换为if ... else语句,但是我发现cond方法更干净。

1 个答案:

答案 0 :(得分:0)

您必须使用_.matches或其他函数,该函数允许您在某些对象中选择属性,而getData则没有上下文,因为您没有传递任何内容,并且_.cond返回了一个有效的函数对一个对象。如果要测试hasLabelsAndTotalsAbove是否为真并执行一些逻辑,则可以创建一个对象并将其传递给_.cond返回的函数:

const totalPosition = 2;
const showLabels = true;
const hasTotalRow = true;

const totalAbove = totalPosition >= 1;
const totalBelow = totalPosition <= -1;

const definitions = {
    hasLabelsAndTotalsAbove: showLabels && totalAbove,
    hasLabelsAndTotalsBelow: showLabels && totalBelow,
    noLabelsAndTotalsAbove: !showLabels && totalAbove,
    noLabelsAndTotalsBelow: !showLabels && totalBelow,
    noTotalHasLabels: showLabels && !hasTotalRow,
    noTotalNoLabels: !showLabels && !hasTotalRow
};

const m = a => _.matches({ [a]: true });

const getData = _.cond([
    [m('hasLabelsAndTotalsAbove'), () => 'Action: hasLabelsAndTotalsAbove'],
    [m('hasLabelsAndTotalsBelow'), () => 'Action: hasLabelsAndTotalsBelow'],
    [m('noLabelsAndTotalsAbove'), () => 'Action: noLabelsAndTotalsAbove'],
    [m('noLabelsAndTotalsBelow'), () => 'Action: noLabelsAndTotalsBelow'],
    [m('noTotalHasLabels'), () => 'Action: noTotalHasLabels'],
    [m('noTotalNoLabels'), () => 'Action: noTotalNoLabels']
]);

console.log(getData(definitions)); 

这使我们可以选择如果对象的某些属性评估为true时要执行的动作。