gpt4 book ai didi

javascript - 使生成器递归函数

转载 作者:行者123 更新时间:2023-11-30 14:44:34 24 4
gpt4 key购买 nike

过滤器有嵌套结构。

{
where: [{
relation: 'user',
query: {
where: [{
relation: 'companies',
query: {
...
}
}]
}
}]
}

我想创建递归函数来生成返回匿名函数的查询类型,匿名函数将参数传递给最终查询。

例如,对于像“user.companies”这样的过滤器查询,它应该返回:

function (fieldQuery) {
return {
where: [{
relation: 'user',
query: {
where: [{
relation: 'companies',
query: fieldQuery
}]
}
}]
}
}

实现该功能的更好方法是什么?

最佳答案

这似乎可行。

// Usage:
fq = 'Some FieldQuery';
filter = 'users.companies.jobs';
result = fieldQuery(fq, filter);

// Recursive function.
// Call with 2 arguments, leave the 3rd one undefined.
function fieldQuery(fq, filter, result=undefined) {
// Index of the last period in filter.
var lastIndex = filter.lastIndexOf('.');
// Starting index of the last relation in filter.
var startsAt = lastIndex + 1

// If the filter is empty (or illegal) we just return the most recent result.
if (lastIndex <= 0 && startsAt >= filter.length) {
return result;
}

// This would be the last relation.
var relation = filter.substr(startsAt);
// The rest of the filter, without the last relation.
var restOfFilter = filter.substr(0, lastIndex);

// Recursive function
return fieldQuery(fq, restOfFilter, {
'where': [{
'relation': relation,
// If result has not been defined before, query is fq.
// Else, query is the previous result.
'query': (typeof(result) === 'undefined') ? fq : result
}]
});
}

关于javascript - 使生成器递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49148522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com