使生成器递归函数

时间:2018-03-07 09:36:41

标签: javascript recursion

过滤器有嵌套结构。

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

我想制作递归函数来生成那种返回匿名函数的查询,该函数将参数传递给最终查询。

例如,对于过滤查询,例如' user.companies'它应该返回:

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

制作该功能的更好方法是什么?

2 个答案:

答案 0 :(得分:1)

这似乎有效。

// 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
    }]
  });
}

答案 1 :(得分:1)

好的,我想出了如何制作这个功能

let queryString = 'user.companies'
let depthArray = queryString.split('.')

function createDepth (depthArray) {

    return fieldQuery => ({
        where: [
            {
                relation: depthArray[0],
                query: depthArray.length <= 1
                    ? fieldQuery
                    : createDepth(depthArray.slice(1))(fieldQuery)
            }
        ]
    })
}