Best JavaScript code snippet using wpt
namespace-prototype-assignment.js
Source:namespace-prototype-assignment.js
1// This test suite compares the behavior of setting the prototype on various values2// (using Object.setPrototypeOf(), obj.__proto__ assignment, and Reflect.setPrototypeOf())3// against what is specified in the ES spec. The expected behavior specified according4// to the spec is expressed in expectationsForObjectSetPrototypeOf,5// expectationsForSetUnderscoreProto, and expectationsForReflectSetPrototypeOf.6import * as namespace from "./namespace-prototype-assignment.js"7var inBrowser = (typeof window != "undefined");8// Test configuration options:9var verbose = false;10var maxIterations = 1;11var throwOnEachError = true;12var testUndefined = true;13var testNull = true;14var testTrue = true;15var testFalse = true;16var testNumbers = true;17var testString = true;18var testSymbol = true;19var testObject = true;20var testGlobal = true;21var testWindowProtos = inBrowser;22var engine;23//====================================================================================24// Error messages:25if (inBrowser) {26 let userAgent = navigator.userAgent;27 if (userAgent.match(/ Chrome\/[0-9]+/)) engine = "chrome";28 else if (userAgent.match(/ Firefox\/[0-9]+/)) engine = "default";29 else engine = "safari";30} else31 engine = "jsc";32// Set default error messages and then override with engine specific ones below.33var DefaultTypeError = "TypeError: ";34var CannotSetPrototypeOfImmutablePrototypeObject = DefaultTypeError;35var CannotSetPrototypeOfThisObject = DefaultTypeError;36var CannotSetPrototypeOfUndefinedOrNull = DefaultTypeError;37var CannotSetPrototypeOfNonObject = DefaultTypeError;38var PrototypeValueCanOnlyBeAnObjectOrNull = DefaultTypeError;39var ObjectProtoCalledOnNullOrUndefinedError = DefaultTypeError;40var ReflectSetPrototypeOfRequiresTheFirstArgumentBeAnObject = DefaultTypeError;41var ReflectSetPrototypeOfRequiresTheSecondArgumentBeAnObjectOrNull = DefaultTypeError;42if (engine == "jsc" || engine === "safari") {43 CannotSetPrototypeOfImmutablePrototypeObject = "TypeError: Cannot set prototype of immutable prototype object";44 CannotSetPrototypeOfThisObject = "TypeError: Cannot set prototype of this object";45 CannotSetPrototypeOfUndefinedOrNull = "TypeError: Cannot set prototype of undefined or null";46 CannotSetPrototypeOfNonObject = "TypeError: Cannot set prototype of non-object";47 PrototypeValueCanOnlyBeAnObjectOrNull = "TypeError: Prototype value can only be an object or null";48 ObjectProtoCalledOnNullOrUndefinedError = "TypeError: Object.prototype.__proto__ called on null or undefined";49 ReflectSetPrototypeOfRequiresTheFirstArgumentBeAnObject = "TypeError: Reflect.setPrototypeOf requires the first argument be an object";50 ReflectSetPrototypeOfRequiresTheSecondArgumentBeAnObjectOrNull = "TypeError: Reflect.setPrototypeOf requires the second argument be either an object or null";51} else if (engine === "chrome") {52 CannotSetPrototypeOfImmutablePrototypeObject = "TypeError: Immutable prototype object ";53}54//====================================================================================55// Utility functions:56if (inBrowser)57 print = console.log;58function reportError(errorMessage) {59 if (throwOnEachError)60 throw errorMessage;61 else62 print(errorMessage);63}64function shouldEqual(testID, resultType, actual, expected) {65 if (actual != expected)66 reportError("ERROR in " + resultType67 + ": expect " + stringify(expected) + ", actual " + stringify(actual)68 + " in test: " + testID.signature + " on iteration " + testID.iteration);69}70function shouldThrow(testID, resultType, actual, expected) {71 let actualStr = "" + actual;72 if (!actualStr.startsWith(expected))73 reportError("ERROR in " + resultType74 + ": expect " + expected + ", actual " + actual75 + " in test: " + testID.signature + " on iteration " + testID.iteration);76}77function stringify(value) {78 if (typeof value == "string") return '"' + value + '"';79 if (typeof value == "symbol") return value.toString();80 if (value === origGlobalProto) return "origGlobalProto";81 if (value === origObjectProto) return "origObjectProto";82 if (value === newObjectProto) return "newObjectProto";83 if (value === proxyObject) return "proxyObject";84 if (value === null) return "null";85 if (typeof value == "object") return "object";86 return "" + value;87}88function makeTestID(index, iteration, targetName, protoToSet, protoSetter, expected) {89 let testID = {};90 testID.signature = "[" + index + "] "91 + protoSetter.actionName + "|"92 + targetName + "|"93 + stringify(protoToSet) + "|"94 + stringify(expected.result) + "|"95 + stringify(expected.proto) + "|"96 + stringify(expected.exception);97 testID.iteration = iteration;98 return testID;99}100//====================================================================================101// Functions to express the expectations of the ES specification:102function doInternalSetPrototypeOf(result, target, origProto, newProto) {103 if (!target.setPrototypeOf) {104 result.success = true;105 result.exception = undefined;106 return;107 }108 target.setPrototypeOf(result, origProto, newProto);109}110// 9.1.2.1 OrdinarySetPrototypeOf ( O, V )111// https://tc39.github.io/ecma262/#sec-ordinarysetprototypeof112function ordinarySetPrototypeOf(result, currentProto, newProto) {113 // 9.1.2.1-4 If SameValue(V, current) is true, return true.114 if (newProto === currentProto) {115 result.success = true;116 return;117 }118 // 9.1.2.1-5 [extensibility check not tested here]119 // 9.1.2.1-8 [cycle check not tested here]120 result.success = true;121}122// 9.4.7.2 SetImmutablePrototype ( O, V )123// https://tc39.github.io/ecma262/#sec-set-immutable-prototype124function setImmutablePrototype(result, currentProto, newProto) {125 if (newProto === currentProto) {126 result.success = true;127 return;128 }129 result.success = false;130 result.exception = CannotSetPrototypeOfImmutablePrototypeObject;131}132// HTML spec: 7.4.2 [[SetPrototypeOf]] ( V )133// https://html.spec.whatwg.org/#windowproxy-setprototypeof134function windowProxySetPrototypeOf(result, currentProto, newProto) {135 result.success = false;136 result.exception = CannotSetPrototypeOfThisObject;137}138var count = 0;139function initSetterExpectation(target, newProto) {140 var targetValue = target.value();141 var origProto = undefined;142 if (targetValue != null && targetValue != undefined)143 origProto = targetValue.__proto__; // Default to old proto.144 var expected = {};145 expected.targetValue = targetValue;146 expected.origProto = origProto;147 expected.exception = undefined;148 expected.proto = origProto;149 expected.result = undefined;150 return expected;151}152// 19.1.2.21 Object.setPrototypeOf ( O, proto )153// https://tc39.github.io/ecma262/#sec-object.setprototypeof154function objectSetPrototypeOf(target, newProto) {155 let expected = initSetterExpectation(target, newProto);156 var targetValue = expected.targetValue;157 var origProto = expected.origProto;158 function throwIfNoExceptionPending(e) {159 if (!expected.exception)160 expected.exception = e;161 }162 // 19.1.2.21-1 Let O be ? RequireObjectCoercible(O).163 if (targetValue == undefined || targetValue == null)164 throwIfNoExceptionPending(CannotSetPrototypeOfUndefinedOrNull);165 // 19.1.2.21-2 If Type(proto) is neither Object nor Null, throw a TypeError exception.166 if (typeof newProto != "object")167 throwIfNoExceptionPending(PrototypeValueCanOnlyBeAnObjectOrNull);168 // 19.1.2.21-3 If Type(O) is not Object, return O.169 else if (typeof targetValue != "object")170 expected.result = targetValue;171 // 19.1.2.21-4 Let status be ? O.[[SetPrototypeOf]](proto).172 else {173 // 19.1.2.21-5 If status is false, throw a TypeError exception.174 let result = {};175 doInternalSetPrototypeOf(result, target, origProto, newProto);176 if (result.success)177 expected.proto = newProto;178 else179 throwIfNoExceptionPending(result.exception);180 // 19.1.2.21-6 Return O.181 expected.result = targetValue;182 }183 return expected;184}185objectSetPrototypeOf.action = (obj, newProto) => Object.setPrototypeOf(obj, newProto);186objectSetPrototypeOf.actionName = "Object.setPrototypeOf";187// B.2.2.1.2 set Object.prototype.__proto__188// https://tc39.github.io/ecma262/#sec-set-object.prototype.__proto__189function setUnderscoreProto(target, newProto) {190 let expected = initSetterExpectation(target, newProto);191 var targetValue = expected.targetValue;192 var origProto = expected.origProto;193 function throwIfNoExceptionPending(e) {194 if (!expected.exception)195 expected.exception = e;196 }197 // B.2.2.1.2-1 Let O be ? RequireObjectCoercible(this value).198 if (targetValue == undefined || targetValue == null)199 throwIfNoExceptionPending(DefaultTypeError);200 // B.2.2.1.2-2 If Type(proto) is neither Object nor Null, return undefined.201 if (typeof newProto != "object")202 expected.result = undefined;203 // B.2.2.1.2-3 If Type(O) is not Object, return undefined.204 else if (typeof targetValue != "object")205 expected.result = undefined;206 // B.2.2.1.2-4 Let status be ? O.[[SetPrototypeOf]](proto).207 else {208 // B.2.2.1.2-5 If status is false, throw a TypeError exception.209 let result = {};210 doInternalSetPrototypeOf(result, target, origProto, newProto);211 if (result.success)212 expected.proto = newProto;213 else214 throwIfNoExceptionPending(result.exception);215 // B.2.2.1.2-6 Return undefined.216 expected.result = undefined;217 }218 // Override the result to be the newProto value because the statement obj.__proto__ = value219 // will produce the rhs value, not the result of the obj.__proto__ setter.220 expected.result = newProto;221 return expected;222}223setUnderscoreProto.action = (obj, newProto) => (obj.__proto__ = newProto);224setUnderscoreProto.actionName = "obj.__proto__";225// 26.1.13 Reflect.setPrototypeOf ( target, proto )226// https://tc39.github.io/ecma262/#sec-reflect.setprototypeof227// function expectationsForReflectSetPrototypeOf(target, newProto, targetExpectation) {228function reflectSetPrototypeOf(target, newProto) {229 let expected = initSetterExpectation(target, newProto);230 var targetValue = expected.targetValue;231 var origProto = expected.origProto;232 function throwIfNoExceptionPending(e) {233 if (!expected.exception)234 expected.exception = e;235 }236 // 26.1.13-1 If Type(target) is not Object, throw a TypeError exception.237 if (targetValue === null || typeof targetValue != "object")238 throwIfNoExceptionPending(ReflectSetPrototypeOfRequiresTheFirstArgumentBeAnObject);239 // 26.1.13-2 If Type(proto) is not Object and proto is not null, throw a TypeError exception.240 if (typeof newProto != "object")241 throwIfNoExceptionPending(ReflectSetPrototypeOfRequiresTheSecondArgumentBeAnObjectOrNull);242 // 26.1.13-3 Return ? target.[[SetPrototypeOf]](proto).243 let result = {};244 doInternalSetPrototypeOf(result, target, origProto, newProto);245 expected.result = result.success;246 if (result.success)247 expected.proto = newProto;248 return expected;249}250reflectSetPrototypeOf.action = (obj, newProto) => Reflect.setPrototypeOf(obj, newProto);251reflectSetPrototypeOf.actionName = "Reflect.setPrototypeOf";252//====================================================================================253// Test Data:254var global = new Function('return this')();255var origGlobalProto = global.__proto__;256var origObjectProto = {}.__proto__;257var proxyObject = new Proxy({ }, {258 setPrototypeOf(target, value) {259 throw "Thrown from proxy";260 }261});262var newObjectProto = { toString() { return "newObjectProto"; } };263var origNamespaceProto = namespace.__proto__;264var targets = [];265targets.push({266 name: "namespace",267 value: () => origNamespaceProto,268 setPrototypeOf: setImmutablePrototype269});270var newProtos = [271 undefined,272 null,273 true,274 false,275 0,276 11,277 123.456,278 "doh",279 Symbol("doh"),280 {},281 origObjectProto,282 origGlobalProto,283 newObjectProto284];285var protoSetters = [286 objectSetPrototypeOf,287 setUnderscoreProto,288 reflectSetPrototypeOf,289];290//====================================================================================291// Test driver functions:292function test(testID, targetValue, newProto, setterAction, expected) {293 let exception = undefined;294 let result = undefined;295 try {296 result = setterAction(targetValue, newProto);297 } catch (e) {298 exception = e;299 }300 shouldThrow(testID, "exception", exception, expected.exception);301 if (!expected.exception) {302 shouldEqual(testID, "__proto__", targetValue.__proto__, expected.proto);303 shouldEqual(testID, "result", result, expected.result);304 }305}306function runTests() {307 let testIndex = 0;308 for (let protoSetter of protoSetters) {309 for (let target of targets) {310 for (let newProto of newProtos) {311 let currentTestIndex = testIndex++;312 for (var i = 0; i < maxIterations; i++) {313 let expected = protoSetter(target, newProto);314 let targetValue = expected.targetValue;315 let testID = makeTestID(currentTestIndex, i, target.name, newProto, protoSetter, expected);316 if (verbose && i == 0)317 print("test: " + testID.signature);318 test(testID, targetValue, newProto, protoSetter.action, expected);319 }320 }321 }322 }323}...
date.js
Source:date.js
1/*2 poly/date3 ES5-ish Date shims for older browsers.4 (c) copyright 2011-2013 Brian Cavalier and John Hann5 This module is part of the cujo.js family of libraries (http://cujojs.com/).6 Licensed under the MIT License at:7 http://www.opensource.org/licenses/mit-license.php8*/9(function (origDate) {10define(['./lib/_base'], function (base) {11 var origProto,12 origParse,13 featureMap,14 maxDate,15 invalidDate,16 isoCompat,17 isoParseRx,18 ownProp,19 undef;20 origProto = origDate.prototype;21 origParse = origDate.parse;22 ownProp = Object.prototype.hasOwnProperty;23 maxDate = 8.64e15;24 invalidDate = NaN;25 // borrowed this from https://github.com/kriskowal/es5-shim26 isoCompat = function () { return origDate.parse('+275760-09-13T00:00:00.000Z') == maxDate; };27 // can't even have spaces in iso date strings28 // in Chrome and FF, the colon in the timezone is optional, but IE, Opera, and Safari need it29 isoParseRx = /^([+\-]\d{6}|\d{4})(?:-(\d{2}))?(?:-(\d{2}))?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:.(\d{1,3}))?)?(?:Z|([+\-])(\d{2})(?::(\d{2}))?)?)?$/;30 featureMap = {31 'date-now': 'now',32 'date-tojson': 'toJSON',33 'date-toisostring': 'toISOString'34 };35 function has (feature) {36 var prop = featureMap[feature];37 return prop in origDate || prop in origProto;38 }39 if (!has('date-now')) {40 origDate.now = function () { return +(new Date); };41 }42 function isInvalidDate (date) {43 return !isFinite(date);44 }45 function fix2 (number) {46 // ensures number is formatted to at least two digits47 return (number < 10 ? '0' : '') + number;48 }49 function isoParse (str) {50 // parses simplified iso8601 dates, such as51 // yyyy-mm-ddThh:mm:ssZ52 // +yyyyyy-mm-ddThh:mm:ss-06:3053 var result;54 // prepare for the worst55 result = invalidDate;56 // fast parse57 str.replace(isoParseRx, function (a, y, m, d, h, n, s, ms, tzs, tzh, tzm) {58 var adjust = 0;59 // Date.UTC handles years between 0 and 100 as 2-digit years, but60 // that's not what we want with iso dates. If we move forward61 // 400 years -- a full cycle in the Gregorian calendar -- then62 // subtract the 400 years (as milliseconds) afterwards, we can avoid63 // this problem. (learned of this trick from kriskowal/es5-shim.)64 if (y >= 0 && y < 100) {65 y = +y + 400; // convert to number66 adjust = -126227808e5; // 400 years67 }68 result = Date.UTC(y, (m || 1) - 1, d || 1, h || 0, n || 0, s || 0, ms || 0) + adjust;69 tzh = +(tzs + tzh); // convert to signed number70 tzm = +(tzs + tzm); // convert to signed number71 if (tzh || tzm) {72 result -= (tzh + tzm / 60) * 36e5;73 // check if time zone is out of bounds74 if (tzh > 23 || tzh < -23 || tzm > 59) result = invalidDate;75 // check if time zone pushed us over maximum date value76 if (result > maxDate) result = invalidDate;77 }78 return ''; // reduces memory used79 });80 return result;81 }82 if (!has('date-toisostring')) {83 origProto.toISOString = function toIsoString () {84 if (isInvalidDate(this)) {85 throw new RangeError("toISOString called on invalid value");86 }87 return [88 this.getUTCFullYear(), '-',89 fix2(this.getUTCMonth() + 1), '-',90 fix2(this.getUTCDate()), 'T',91 fix2(this.getUTCHours()), ':',92 fix2(this.getUTCMinutes()), ':',93 fix2(this.getUTCSeconds()), '.',94 (this.getUTCMilliseconds()/1000).toFixed(3).slice(2), 'Z'95 ].join('');96 };97 }98 if (!has('date-tojson')) {99 origProto.toJSON = function toJSON (key) {100 // key arg is ignored by Date objects, but since this function101 // is generic, other Date-like objects could use the key arg.102 // spec says to throw a TypeError if toISOString is not callable103 // but that's what happens anyways, so no need for extra code.104 return this.toISOString();105 };106 }107 function checkIsoCompat () {108 // fix Date constructor109 var newDate = (function () {110 // Replacement Date constructor111 return function Date (y, m, d, h, mn, s, ms) {112 var len, result;113 // Date called as function, not constructor114 if (!(this instanceof newDate)) return origDate.apply(this, arguments);115 len = arguments.length;116 if (len === 0) {117 result = new origDate();118 }119 else if (len === 1) {120 result = new origDate(base.isString(y) ? newDate.parse(y) : y);121 }122 else {123 result = new origDate(y, m, d == undef ? 1 : d, h || 0, mn || 0, s || 0, ms || 0);124 }125 result.constructor = newDate;126 return result;127 };128 }());129 if (!isoCompat()) {130 newDate.now = origDate.now;131 newDate.UTC = origDate.UTC;132 newDate.prototype = origProto;133 newDate.prototype.constructor = newDate;134 newDate.parse = function parse (str) {135 var result;136 // check for iso date137 result = isoParse('' + str);138 if (isInvalidDate(result)) {139 // try original parse()140 result = origParse(str);141 }142 return result;143 };144 // Unfortunate. See cujojs/poly#11145 // Copy any owned props that may have been previously added to146 // the Date constructor by 3rd party libs.147 copyPropsSafely(newDate, origDate);148 Date = newDate;149 }150 else if (Date != origDate) {151 Date = origDate;152 }153 }154 function copyPropsSafely(dst, src) {155 for (var p in src) {156 if (ownProp.call(src, p) && !ownProp.call(dst, p)) {157 dst[p] = src[p];158 }159 }160 }161 checkIsoCompat();162 return {163 setIsoCompatTest: function (testFunc) {164 isoCompat = testFunc;165 checkIsoCompat();166 }167 };168});...
extendObject.js
Source:extendObject.js
1module.exports = function (base, sub) {2 // Avoid instantiating the base class just to setup inheritance3 // Also, do a recursive merge of two prototypes, so we don't overwrite4 // the existing prototype, but still maintain the inheritance chain5 // Thanks to @ccnokes6 var origProto = sub.prototype;7 sub.prototype = Object.create(base.prototype);8 for (var key in origProto) {9 sub.prototype[key] = origProto[key];10 }11 // The constructor property was set wrong, let's fix it12 Object.defineProperty(sub.prototype, 'constructor', {13 enumerable: false,14 value: sub15 });...
Using AI Code Generation
1var wpt = require('webpagetest');2var origProto = wpt.prototype;3var WebPageTest = function(options) {4 var instance = new origProto(options);5 var origGet = instance.getTestResults;6 instance.getTestResults = function(testId, cb) {7 origGet.call(instance, testId, function(err, data) {8 if (err) {9 return cb(err);10 }11 cb(null, data);12 });13 };14 return instance;15};16module.exports = WebPageTest;
Using AI Code Generation
1var wpt = require('webpagetest');2var origProto = wpt.prototype;3var wpt = new wpt('API_KEY');4wpt.prototype = origProto;5 if (err) return console.log(err);6 console.log(data);7});8I'm not sure why this is happening. I've tried to do this with other functions as well and I've gotten the same error. When I try to run the code without the line wpt.prototype = origProto; I get the error:9wpt.prototype.test = function (url, callback) {10}
Using AI Code Generation
1var origProto = wpt.__proto__;2var origMethod = origProto.method;3origProto.method = function() {4 console.log('test');5 return origMethod.apply(this, arguments);6};7wpt.method();
Using AI Code Generation
1var origProto = wp.textpattern.prototype;2wp.textpattern = function( ed, url ) {3 origProto.call( this, ed, url );4}5origProto.prototype.init = function() {6}7origProto.prototype._getPatterns = function() {8}9origProto.prototype._replace = function( ed, e, data ) {10}11origProto.prototype._replaceShortcode = function( ed, e, data ) {12}13origProto.prototype._replacePattern = function( ed, e, data ) {14}15origProto.prototype._getSelection = function( ed, e ) {16}17origProto.prototype._getSelectionRange = function( ed, e ) {18}19origProto.prototype._getSelectionParent = function( ed, e ) {20}21origProto.prototype._getSelectionText = function( ed, e ) {22}23origProto.prototype._getSelectionStart = function( ed, e ) {24}25origProto.prototype._getSelectionEnd = function( ed, e ) {26}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!