|
| 1 | + |
| 2 | +const utils = require('./utils') |
| 3 | + |
| 4 | +function planner (query) { |
| 5 | + if (query.length === 1) return query |
| 6 | + // first group queries based on number of variables. |
| 7 | + const solved = new Set() |
| 8 | + var grouped = query.reduce((ordered, q) => { |
| 9 | + const variables = utils.variableNames(q) |
| 10 | + if (ordered[variables.length]) { |
| 11 | + ordered[variables.length].push({ |
| 12 | + query: q, |
| 13 | + names: variables |
| 14 | + }) |
| 15 | + } else { |
| 16 | + ordered[variables.length] = [{ |
| 17 | + query: q, |
| 18 | + names: variables |
| 19 | + }] |
| 20 | + } |
| 21 | + if (variables.length === 1) { |
| 22 | + solved.add(variables[0]) |
| 23 | + } |
| 24 | + return ordered |
| 25 | + }, []) |
| 26 | + // then order vars > 1 by if they occur in |
| 27 | + const orderedQueries = grouped[1] ? grouped[1].map(v => v.query) : [] |
| 28 | + |
| 29 | + for (let i = 2; i < grouped.length; i++) { |
| 30 | + if (grouped[i] === undefined) continue |
| 31 | + while (grouped[i].length > 0) { |
| 32 | + // get the next easiest to solve |
| 33 | + // or the one that makes the rest easiest to solve |
| 34 | + grouped[i].sort((a, b) => { |
| 35 | + // number of unsolved variables |
| 36 | + let unsolvedA = a.names.filter(name => !solved.has(name)) |
| 37 | + let unsolvedB = b.names.filter(name => !solved.has(name)) |
| 38 | + if (unsolvedA.length < unsolvedB.length) return -1 |
| 39 | + if (unsolvedA.length > unsolvedB.length) return 1 |
| 40 | + // calculate how many unsolved vars it has in common with others in the group |
| 41 | + // should this be a vector? many vars is better than solving 1 lots. |
| 42 | + let sharedUnsolvedA = 0 |
| 43 | + let sharedUnsolvedB = 0 |
| 44 | + grouped[i].forEach(v => { |
| 45 | + v.names.forEach((name) => { |
| 46 | + if (solved.has(name)) return |
| 47 | + if (v !== a && a.names.includes(name)) sharedUnsolvedA++ |
| 48 | + if (v !== b && b.names.includes(name)) sharedUnsolvedB++ |
| 49 | + }) |
| 50 | + }) |
| 51 | + if (sharedUnsolvedA > sharedUnsolvedB) return -1 |
| 52 | + if (sharedUnsolvedA < sharedUnsolvedB) return 1 |
| 53 | + return 0 |
| 54 | + }) |
| 55 | + const next = grouped[i].shift() |
| 56 | + orderedQueries.push(next.query) |
| 57 | + next.names.forEach(n => solved.add(n)) |
| 58 | + } |
| 59 | + } |
| 60 | + return orderedQueries |
| 61 | +}; |
| 62 | + |
| 63 | +module.exports = planner |
0 commit comments