Skip to content

Instantly share code, notes, and snippets.

@yesmar
Created January 26, 2018 23:15
Show Gist options
  • Save yesmar/06c81c26435f3d358d238ab60d89a07b to your computer and use it in GitHub Desktop.
Save yesmar/06c81c26435f3d358d238ab60d89a07b to your computer and use it in GitHub Desktop.
Run code through the Chrome debugger with an optional args parameter
(function() {
'use strict';
function runWithDebugger(f, args) {
if (typeof f !== 'function') { throw 'f must be a function' }
// The apply() method treats unspecified args or null or undefined args as 'no args'.
if (args === undefined || typeof args === 'object' && (args === null || Array.isArray(args))) {
debugger;
f.apply(null, args);
} else {
throw 'args must be an array, null or undefined';
}
}
window.runWithDebugger = runWithDebugger;
})();
@yesmar
Copy link
Author

yesmar commented Jan 27, 2018

If args is not specified it is treated as undefined, which tells the apply method that there are no arguments. (See Function.prototype.apply() for details.)

Test cases

function sayHi() {
  console.log('hi!');
}

runWithDebugger(sayHi); // 'hi!'
function sayHiTo(name) {
  console.log('hi ' + name);
}

runWithDebugger(sayHiTo, ['foobaz']); // 'hi foobaz'
function sayFullName(first, last) {
  console.log(first + ' '  + last);
}

runWithDebugger(sayFullName, ['foobaz', 'quux']); // 'foobaz quux'

Additional test cases

runWithDebugger(sayHi, null); // 'hi'
runWithDebugger(sayHi, undefined); // 'hi'
runWithDebugger(sayHi, []); // 'hi'
runWithDebugger(sayHi, {}); // 'Uncaught args must be an array, null or undefined'
runWithDebugger('sayHi', []); // 'Uncaught f must be a function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment