Random sorting

It should be plenty possible to implement @Daniel_Steigerwald’s pseudorandom number generator directly in FQL where you would provide access to a UDF Create function but not the standard one. Daniel’s links are rather esoteric, but the code there is an easy example of what can be done. The seed value can be stored in the data for the function, and interestingly enough, a function can update itself!

This implements the code above in FQL for a UDF named “srng”

Query(
  Lambda(
    [],
    Let(
      {
        seed: Select(["data", "seed"], Get(Function("srng")), 1),
        nextSeed: Modulo(
          Add(Multiply(1839567234, Var("seed")), 972348567),
          8239451023
        ),
        functionUpdate: Update(Function("srng"), {
          data: { seed: Var("nextSeed") }
        })
      },
      Var("nextSeed")
    )
  )
)

UPDATE 2024-05-02

WARNING: mutating schema in an unbounded manner like this is highly discouraged. History retention on schema is infinite, so updates like this will be problematic for reads and storage. Additionally, reading a resource and updating it transactionally is prone to contention when it occurs often. An operation like this would basically be limited to about 5 requests concurrent requests.

One alternative could be to save the seed in a document owned by the caller. That way you avoid both history issues as well as contention with other callers (assuming the caller does not make many concurrent requests)

2 Likes