<commit_before>const EventEmitter = require('events')
const { KafkaJSLockTimeout } = require('../errors')

module.exports = class Lock {
  constructor({ timeout = 1000 } = {}) {
    this.locked = false
    this.timeout = timeout
    this.emitter = new EventEmitter()
  }

  async acquire() {
    return new Promise((resolve, reject) => {
      if (!this.locked) {
        this.locked = true
        return resolve()
      }

      let timeoutId
      const tryToAcquire = () => {
        if (!this.locked) {
          this.locked = true
          clearTimeout(timeoutId)
          this.emitter.removeListener('releaseLock', tryToAcquire)
          return resolve()
        }
      }

      this.emitter.on('releaseLock', tryToAcquire)
      timeoutId = setTimeout(
        () => reject(new KafkaJSLockTimeout('Timeout while acquiring lock')),
        this.timeout
      )
    })
  }

  async release() {
    this.locked = false
    setImmediate(() => this.emitter.emit('releaseLock'))
  }
}<commit_msg>Rewrite Lock to remove the need of EventEmitter<commit_after>const { KafkaJSLockTimeout } = require('../errors')

const PRIVATE = {
  LOCKED: Symbol('private:Lock:locked'),
  TIMEOUT: Symbol('private:Lock:timeout'),
  WAITING: Symbol('private:Lock:waiting'),
}

module.exports = class Lock {
  constructor({ timeout = 1000 } = {}) {
    this[PRIVATE.LOCKED] = false
    this[PRIVATE.TIMEOUT] = timeout
    this[PRIVATE.WAITING] = new Set()
  }

  async acquire() {
    return new Promise((resolve, reject) => {
      if (!this[PRIVATE.LOCKED]) {
        this[PRIVATE.LOCKED] = true
        return resolve()
      }

      let timeoutId
      const tryToAcquire = async () => {
        if (!this[PRIVATE.LOCKED]) {
          this[PRIVATE.LOCKED] = true
          clearTimeout(timeoutId)
          this[PRIVATE.WAITING].delete(tryToAcquire)
          return resolve()
        }
      }

      this[PRIVATE.WAITING].add(tryToAcquire)
      timeoutId = setTimeout(
        () => reject(new KafkaJSLockTimeout('Timeout while acquiring lock')),
        this[PRIVATE.TIMEOUT]
      )
    })
  }

  async release() {
    this[PRIVATE.LOCKED] = false
    const waitingForLock = Array.from(this[PRIVATE.WAITING])
    return Promise.all(waitingForLock.map(acquireLock => acquireLock()))
  }
}
{'fraction_non_alphanumeric': 0.13184406482698205, 'fraction_numerical': 0.003504161191414805, 'mean_word_length': 2.6253968253968254, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6391830', 'n_tokens_mistral': 702, 'n_tokens_neox': 682, 'n_words': 135}