RamdaJS:组合一个对象产生相同的 "random" 结果

RamdaJS: Composing an object produces the same "random" results

我正在研究 Ramda,试图了解函数式 JS。以下代码是尝试生成一些随机搜索过滤器对象:

var R = require('ramda');
var rWords = require('random-words');

var types = ['keyword', 'phrase', 'domain', 'person'];
var operands = ['AND', 'OR', 'NOT'];

var getRandom = (min=1, max=10) => Math.floor(Math.random() * (max - min)) + min;
var sample = (arr) => arr[getRandom(0, arr.length)];
var chooseWords = (min=1, max=getRandom()) => rWords({min, max, join: ' '});
var chooseWordsFromType = (obj) => {
    var max = obj.type === 'phrase' ? 10 : 1;
    query = chooseWords(1, max);
    return R.merge({query}, obj);
};

var makeFilter = R.compose(
    chooseWordsFromType,
    R.merge({operand: sample(operands)}),
    R.merge({type: sample(types)})
);

var initial = [];
for(var i = 0; i < getRandom(); i++){
    initial.push(makeFilter({}));
}
console.log(initial);

预期的结果应该是这样的

[
  {type: 'keyword', operand: 'AND', query:['something']},
  {type: 'domain', operand: 'AND', query:['something_else']}
]

错误在于 initial 中的所有内容都具有完全相同的操作数和类型;只有查询本身不同。我猜它会记住对 sample 的调用,但我不知道为什么。

顺便说一句,我如何重构 chooseWordsFromType 以便在不需要 return 对象的情况下进行组合?或者我可以吗?

您希望从这段代码中得到什么?:

var defaultOperands = {operand: sample(operands)};
var defaultTypess = {type: sample(types)};

var makeFilter = R.compose(
    chooseWordsFromType,
    R.merge({operand: defaultOperands}),
    R.merge({type: defaultTypes})
);

您的代码:

var makeFilter = R.compose(
    chooseWordsFromType,
    R.merge({operand: sample(operands)}),
    R.merge({type: sample(types)})
);

做很多相同的事情,本质上说,"call sample, passing in operands, make an object out of that, keyed by 'operand'",做与 types 和 'type' 类似的事情,然后创建一个 makeFilter 函数,它将将这些静态对象中的每一个与您的输入和 return 将其传递给 chooseWordsFromType.

的结果合并

使它动态化的一种(未经测试的)方法是:

var makeFilter = R.compose(
    chooseWordsFromType,
    obj => R.merge({operand: sample(operands)}, obj),
    obj => R.merge({type: sample(types)}, obj)
);