JSFiddle - React, Tailwind, and code Playground

by Danny Michaelis

JavaScript

function parse(jsonObj) {
  if (typeof jsonObj === 'string') return JSON.parse(jsonObj);
  return jsonObj || {};
}

function stringify(obj, replace = null, spacing = 4) {
  if (!obj) return '';
  if (typeof obj === 'string') return obj;
  return JSON.stringify(obj, replace, spacing)
}

class GlobalLogger {
	constructor ( ...tags )
  {		
  	this.tags = new Set( tags );
  }
  addTag( tag ) 
  {
    this.tags[tag] = true;
    return this
  }
  
  log(...args) 
  {
    console.log(...args);
    return this;
  }
  
  pretty( arg, replace = null, spacing = 4 )
  {
    console.log(stringify(arg, replace, spacing))
    return this
  }
  
  if( bool ) // This is the name of a function, not an if-statment
  {
  	return {
    	then: ( ...args ) => {
      	if ( bool ) console.log( ...args );
        return {
        	else: ( ...otherArgs ) => { if ( !bool ) console.log( ...otherArgs ) }
        }
      }
    }

  }
  
  tag(...tags)
  {
    // if (tags.some((tag) => this.tags[tag])) return this
		if ( tags.some( tag => this.tags.has( tag ) ) ) return this;
    return {
      log: (...args) => '',
      pretty: (...args) => '',
    }
  }
}

let C = new GlobalLogger();
C.addTag( 'test' );

C.log( 'something' );

const obj = {x: { y: { z: 0 } } };

C.log( obj ).pretty( obj );

// Won't print
C.tag( 'obj' ).log( 'No Tag' );

C.tag( 'obj', 'x' ).log( 'Tagged' );

C.tag( 0 ).log( 'Tagged' );

// Will print
C.tag( 'test' ).log( 'test? Tagged!' );

C.tag( 'obj', 'test' ).log( 'obj? test? Tagged!' );

C.if( true ).then( 'true' ).else( 'false' )
C.if( false ).then( 'true' ).else( 'false' )