id-generator.js 785 B

1234567891011121314151617181920212223
  1. 'use strict'
  2. const { MAX_MSGID } = require('../constants')
  3. /**
  4. * Returns a function that generates message identifiers. According to RFC 4511
  5. * the identifers should be `(0, MAX_MSGID)`. The returned function handles
  6. * this and wraps around when the maximum has been reached.
  7. *
  8. * @param {integer} [start=0] Starting number in the identifier sequence.
  9. *
  10. * @returns {function} This function accepts no parameters and returns an
  11. * increasing sequence identifier each invocation until it reaches the maximum
  12. * identifier. At this point the sequence starts over.
  13. */
  14. module.exports = function idGeneratorFactory (start = 0) {
  15. let currentID = start
  16. return function nextID () {
  17. const id = currentID + 1
  18. currentID = (id >= MAX_MSGID) ? 1 : id
  19. return currentID
  20. }
  21. }