How to make DRY logger class with debug, info, warn and error methods that extends private method I am trying to make logger class with debug, info, warn and error methods that &quot;extends&quot; basic log method.
However it is not written using DRY principle, how can I make it DRY, not WET?
Code snippet


const logLevels = {
  0: 'debug',
  1: 'info',
  2: 'warn',
  3: 'error',
  'debug': 0,
  'info': 1,
  'warn': 2,
  'error': 3,
}

class Logger {
  logLevel = logLevels.debug

  log(logLevel, ...messages) {
    if (logLevel &gt;= this.logLevel) {
      const logType = logLevels[logLevel]
      messages.unshift(logType)

      console.log(...messages)
    }
  }

  debug(...messages) {
    this.log(logLevels.debug, ...messages)
  }

  info(...messages) {
    this.log(logLevels.info, ...messages)
  }

  warn(...messages) {
    this.log(logLevels.warn, ...messages)
  }

  error(...messages) {
    this.log(logLevels.error, ...messages)
  }
}

const myLogger = new Logger()
const dateNowHex = () =&gt; Date.now().toString(16)

myLogger.debug('this is a test', dateNowHex())
myLogger.info('this is a test', dateNowHex())
myLogger.warn('this is a test', dateNowHex())
myLogger.error('this is a test', dateNowHex())



Should I make better class composition? Can you provide examples?
Interesting question;

getting the logType and then unshifting it seems complicated, why not
console.log(logLevels[logLevel], ...messages)

The mapping from an integer to a string and back from string to integer must be addressed to make this DRY

This code seems a good fit for monads, which can also help with making this DRY


Other than that there is not much to say.


function Logger() {
  
  const logLevels = ['debug', 'info', 'warn', 'error'];
  this.logLevel = 0;

  this.log = function log(logLevel, ...messages) {
    if (logLevel &gt;= this.logLevel) {
      console.log(logLevels[logLevel], ...messages)
    }
  }
  
  for(let i = 0; i&lt; logLevels.length; i++){
    this[logLevels[i]] = this.log.bind(this, i);
  }

} 

const myLogger = new Logger()
const dateNowHex = () =&gt; Date.now().toString(16) 
//debugger; 
myLogger.debug('this is a test', dateNowHex())
myLogger.info('this is a test', dateNowHex())
myLogger.warn('this is a test', dateNowHex())
myLogger.error('this is a test', dateNowHex())