How to get rid of duplicate code?

  • 0
    Hello! There is a piece of code:

    this.more.addEventListener('click', (e) => {
    				if ( !this.more.classList.contains('inactive') ) {
    					this.mores(board, cards_obj);
    					this.double.classList.add('inactive');
    				}
    			});
    
    			this.double.addEventListener('click', (e) => {
    				if ( !this.double.classList.contains('inactive') ) {
    					this.dual(board, cards_obj);
    					this.double.classList.add('inactive');
    				}
    			});


    They differ only in the condition and the functions called inside it, and in order to get rid of code duplication, I want to create a separate function that will take the function arguments inside the condition, but for some reason they do not want to be passed correctly.

    How to implement all this correctly?
    JavaScript Anonymous, Dec 15, 2020

  • 1 Answers
  • 0
    Alternatively



    function myFunc(el, container){
    if ( !el.classList.contains('inactive') ) {
    this[container](board, cards_obj);
    el.classList.add('inactive');
    }
    }

    this.more.addEventListener('click', e => myFunc(e.target, 'mores'));
    this.double.addEventListener('click', e => myFunc(e.target, 'dual'));




    But still, something is not right here.
    Juliette Dennis

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!