export function generateQueries()

in dashboard/new-dashboard/src/components/common/DataQueryExecutor.ts [84:171]


export function generateQueries(query: DataQuery, configuration: DataQueryExecutorConfiguration): DataQuery[] {
  let producers = configuration.queryProducers
  if (producers.length === 0) {
    producers = [
      {
        size(): number {
          return 1
        },
        getMeasureName(_index: number): string {
          return configuration.measures[0]
        },
        getSeriesName(_index: number): string {
          return configuration.measures[0]
        },
        mutate(): void {
          // the only value
        },
      },
    ]
  }

  const cartesian: number[][] =
    producers.length === 1
      ? Array.from({ length: producers[0].size() }).map((_, i) => [i])
      : computeCartesian(
          producers.map((it) => {
            return Array.from({ length: it.size() }).map((_, i) => i)
          })
        )

  let serializedQuery = []

  // https://en.wikipedia.org/wiki/Cartesian_product

  const result: DataQuery[] = []
  const last = Array.from({ length: producers.length - 1 }).map((_, i) => cartesian[0][i])
  for (const item of cartesian) {
    // each column it is a producer
    // each row it is a combination
    // each column value it is an index of producer value
    let seriesName = ""
    let measureName = ""
    for (const [i, index] of item.entries()) {
      const producer = producers[i]
      producer.mutate(index)
      if (i !== 0) {
        measureName += " – "
      }
      measureName += producer.getMeasureName(index)

      const title = producer.getSeriesName(index)
      if (title.length > 0) {
        if (seriesName.length > 0) {
          seriesName += " – "
        }
        seriesName += title
      }
    }

    serializedQuery.push(structuredClone(query))

    if (item.length > 1) {
      let equal = true
      for (let i = item.length - 2; i >= 0; i--) {
        if (last[i] != item[i]) {
          for (let j = 0, n = item.length - 1; j < n; j++) {
            last[j] = item[j]
          }
          equal = false
          break
        }
      }

      if (!equal) {
        result.push(...serializedQuery)
        serializedQuery = []
      }
    }

    configuration.seriesNames.push(seriesName)
    configuration.measureNames.push(measureName)
  }

  if (serializedQuery.length > 0) {
    result.push(...serializedQuery)
  }
  return result
}