rand-server.js 978 Bytes
const http = require('http')

// The parameters of a linear congruential generator.
// See https://en.wikipedia.org/wiki/Linear_congruential_generator.
const A = 48271
const M = 2 ** 31 - 1

// The last value returned from the generator.
// The initial value is the "seed".
let lastValue = 1

http.createServer((req, res) => {
  if (req.url === '/seed') {
    // POSTing to `/seed` sets the seed of the generator
    let body = ''
    req.setEncoding('utf8')
      .on('data', chunk => {
        // Concatenate request body into a single string
        body += chunk
      })
      .on('end', () => {
        // Parse the JSON request body and extract the seed
        lastValue = JSON.parse(body).seed
        // Send an empty response
        res.end()
      })
  }
  else {
    // GETing `/next` updates the generator
    // and responds with the new value
    lastValue = (lastValue * A) % M
    res.write(JSON.stringify({value: lastValue}))
    res.end()
  }
}).listen(80)