JSFiddle - React, Tailwind, and code Playground

by Csaba Hellinger

HTML

<div id="test"></div>

JavaScript

function tryToCallApi(apiName, params = []) {
	let thisArg = null;
    const api = apiName
    	.split('.')
        .reduce((acc, current) => {
        	thisArg = acc;
        	return acc[current] || {}
        }, window);
    
    //console.log('api', api);
    //console.log('this', thisArg);
        
    if (typeof api === 'function') {
    	return api.apply(thisArg, params);
    }
}

tryToCallApi('console.clear');                     // calls it
tryToCallApi('document.getElementById', ['test'])  // returns the <div/>
tryToCallApi('console.log', ['1', '2', '3'])  // returns the <div/>

tryToCallApi('document.missingFunc', ['1', '2'])   // nothing