diff --git a/lib/vm.js b/lib/vm.js index c9bb44f05732c9..78a2de16d38603 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -79,22 +79,23 @@ Script.prototype.runInNewContext = function(sandbox, options) { return this.runInContext(context, options); }; +function validateString(prop, propName) { + if (prop !== undefined && typeof prop !== 'string') + throw new errors.TypeError('ERR_INVALID_ARG_TYPE', propName, + 'string', prop); +} + function getContextOptions(options) { - const contextOptions = options ? { - name: options.contextName, - origin: options.contextOrigin - } : {}; - if (contextOptions.name !== undefined && - typeof contextOptions.name !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.contextName', - 'string', contextOptions.name); - } - if (contextOptions.origin !== undefined && - typeof contextOptions.origin !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.contextOrigin', - 'string', contextOptions.origin); + if (options) { + const contextOptions = { + name: options.contextName, + origin: options.contextOrigin + }; + validateString(contextOptions.name, 'options.contextName'); + validateString(contextOptions.origin, 'options.contextOrigin'); + return contextOptions; } - return contextOptions; + return {}; } let defaultContextNameIndex = 1; @@ -120,10 +121,7 @@ function createContext(sandbox, options) { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.name', 'string', options.name); } - if (options.origin !== undefined && typeof options.origin !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.origin', - 'string', options.origin); - } + validateString(options.origin, 'options.origin'); } else { options = { name: `VM Context ${defaultContextNameIndex++}`