Best JavaScript code snippet using best
transforms.test.ts
Source:transforms.test.ts
1import { Hub } from '../src/types'2import { createHub } from '../src/utils/db/hub'3import { code } from '../src/utils/utils'4import { transformCode } from '../src/worker/vm/transforms'5import { resetTestDatabase } from './helpers/sql'6describe('transforms', () => {7 let hub: Hub8 let closeHub: () => Promise<void>9 beforeEach(async () => {10 ;[hub, closeHub] = await createHub()11 await resetTestDatabase(`const processEvent = event => event`)12 })13 afterEach(async () => {14 await closeHub()15 })16 describe('transformCode', () => {17 it('secures awaits by wrapping promises in __asyncGuard', () => {18 const rawCode = code`19 async function x() {20 await console.log()21 }22 `23 const transformedCode = transformCode(rawCode, hub)24 expect(transformedCode).toStrictEqual(code`25 "use strict";26 async function x() {27 await __asyncGuard(console.log(), console.log);28 }29 `)30 })31 it('attaches caller information to awaits', () => {32 const rawCode = code`33 async function x() {34 await anotherAsyncFunction('arg1', 'arg2')35 }36 `37 const transformedCode = transformCode(rawCode, hub)38 expect(transformedCode).toStrictEqual(code`39 "use strict";40 async function x() {41 await __asyncGuard(anotherAsyncFunction('arg1', 'arg2'), anotherAsyncFunction);42 }43 `)44 })45 it('attaches caller information to awaits for anonymous functions', () => {46 const rawCode = code`47 async function x() {48 await (async () => {console.log()})49 }50 `51 const transformedCode = transformCode(rawCode, hub)52 expect(transformedCode).toStrictEqual(code`53 "use strict";54 async function x() {55 await __asyncGuard(async () => {56 console.log();57 }, async () => {58 console.log();59 });60 }61 `)62 })63 it('secures then calls by wrapping promises in __asyncGuard', () => {64 const rawCode = code`65 async function x() {}66 x.then(() => null)67 `68 const transformedCode = transformCode(rawCode, hub)69 expect(transformedCode).toStrictEqual(code`70 "use strict";71 async function x() {}72 __asyncGuard(x).then(() => null);73 `)74 })75 it('secures block for loops with timeouts', () => {76 const rawCode = code`77 for (let i = 0; i < i + 1; i++) {78 console.log(i)79 }80 `81 const transformedCode = transformCode(rawCode, hub)82 expect(transformedCode).toStrictEqual(code`83 "use strict";84 const _LP = Date.now();85 for (let i = 0; i < i + 1; i++) {86 if (Date.now() - _LP > 30000) throw new Error("Script execution timed out after looping for 30 seconds on line 1:0");87 console.log(i);88 }89 `)90 })91 it('secures inline for loops with timeouts', () => {92 const rawCode = code`93 for (let i = 0; i < i + 1; i++) console.log(i)94 `95 const transformedCode = transformCode(rawCode, hub)96 expect(transformedCode).toStrictEqual(code`97 "use strict";98 const _LP = Date.now();99 for (let i = 0; i < i + 1; i++) {100 if (Date.now() - _LP > 30000) throw new Error("Script execution timed out after looping for 30 seconds on line 1:0");101 console.log(i);102 }103 `)104 })105 it('secures block for loops with timeouts avoiding _LP collision', () => {106 const rawCode = code`107 const _LP = 0108 for (let i = 0; i < i + 1; i++) {109 console.log(i)110 }111 `112 const transformedCode = transformCode(rawCode, hub)113 expect(transformedCode).toStrictEqual(code`114 "use strict";115 const _LP = 0;116 const _LP2 = Date.now();117 for (let i = 0; i < i + 1; i++) {118 if (Date.now() - _LP2 > 30000) throw new Error("Script execution timed out after looping for 30 seconds on line 3:0");119 console.log(i);120 }121 `)122 })123 it('transforms TypeScript to plain JavaScript', () => {124 const rawCode = code`125 interface Y {126 a: int127 b: string128 }129 function k({ a, b }: Y): string {130 return \`a * 10 is {a * 10}, while b is just {b}\`131 }132 let a: int = 2133 console.log(k({ a, b: 'tomato' }))134 `135 const transformedCode = transformCode(rawCode, hub)136 expect(transformedCode).toStrictEqual(code`137 "use strict";138 function k({139 a,140 b141 }) {142 return \`a * 10 is {a * 10}, while b is just {b}\`;143 }144 let a = 2;145 console.log(k({146 a,147 b: 'tomato'148 }));149 `)150 })151 it('replaces imports', () => {152 const rawCode = code`153 import { bla, bla2, bla3 as bla4 } from 'node-fetch'154 import fetch1 from 'node-fetch'155 import * as fetch2 from 'node-fetch'156 console.log(bla, bla2, bla4, fetch1, fetch2);157 `158 const transformedCode = transformCode(rawCode, hub, { 'node-fetch': { bla: () => true } })159 expect(transformedCode).toStrictEqual(code`160 "use strict";161 const bla = __pluginHostImports["node-fetch"]["bla"],162 bla2 = __pluginHostImports["node-fetch"]["bla2"],163 bla4 = __pluginHostImports["node-fetch"]["bla3"];164 const fetch1 = __pluginHostImports["node-fetch"];165 const fetch2 = __pluginHostImports["node-fetch"];166 console.log(bla, bla2, bla4, fetch1, fetch2);167 `)168 })169 it('only replaces provided imports', () => {170 const rawCode = code`171 import { kea } from 'kea'172 console.log(kea)173 `174 expect(() => {175 transformCode(rawCode, hub, { 'node-fetch': { default: () => true } })176 }).toThrow("/index.ts: Cannot import 'kea'! This package is not provided by PostHog in plugins.")177 })178 it('replaces requires', () => {179 const rawCode = code`180 const fetch = require('node-fetch')181 const { BigQuery } = require('@google-cloud/bigquery')182 console.log(fetch, BigQuery);183 `184 const transformedCode = transformCode(rawCode, hub, {185 'node-fetch': { bla: () => true },186 '@google-cloud/bigquery': { BigQuery: () => true },187 })188 expect(transformedCode).toStrictEqual(code`189 "use strict";190 const fetch = __pluginHostImports["node-fetch"];191 const {192 BigQuery193 } = __pluginHostImports["@google-cloud/bigquery"];194 console.log(fetch, BigQuery);195 `)196 })197 it('only replaces provided requires', () => {198 const rawCode = code`199 const { kea } = require('kea')200 console.log(kea)201 `202 expect(() => {203 transformCode(rawCode, hub, { 'node-fetch': { default: () => true } })204 }).toThrow("/index.ts: Cannot import 'kea'! This package is not provided by PostHog in plugins.")205 })206 })...
main.js
Source:main.js
1$(document).ready(function() {2 var rawInput = "";3 $('#clearButton').hide();4 //$('#runningIndicator').hide();5 $('#brainfuckCode').bind('input propertychange', function() {6 $("#brainfuckInputLabel").hide();7 if (!$('#runButton').hasClass('disabled')) $('#runButton').addClass('disabled');8 if (this.value.length > 0) {9 $('#runButton').removeClass('disabled');10 if (this.value.indexOf(",") > -1) $("#brainfuckInputLabel").show();11 }12 });13 $('#runButton').click(function() {14 rawInput = $('#brainfuckInput').val() + String.fromCharCode(0);15 if (!$('#runButton').hasClass('disabled')) {16 //$('#runningIndicator').show();17 $('#brainfuckOutput').val(execute($('#brainfuckCode').val().replace(/\s+/g, ''))[2]).trigger('propertychange');18 //$('#runningIndicator').hide();19 }20 });21 $('#debugmodeButton').click(function() {22 sweetAlert("Oops...", "Debug mode has not been implemented yet.", "error");23 });24 $('#brainfuckOutput').bind('input propertychange', function() {25 $('#clearButton').hide();26 if (this.value.length > 0) {27 $('#clearButton').show();28 }29 });30 $('#clearButton').click(function() {31 $('#brainfuckOutput').val("").trigger('propertychange');32 });33 var loopedCode = function(rawCode) {34 var leftCount = 0,35 rightCount = 0;36 for (var i = 0; i < rawCode.length; i++) {37 if (rawCode.charCodeAt(i) === 91) leftCount++;38 else if (rawCode.charCodeAt(i) === 93) rightCount++;39 if (leftCount === rightCount && leftCount !== 0) return rawCode.substring(1, i);40 }41 }42 var execute = function(rawCode, index, data, output) {43 //--//INIT\\--\\44 index = index || 0;45 if (!data) {46 data = [];47 for (var i = 0; i < 10000; i++) data.push(0);48 }49 output = output || "";50 console.log(rawCode + "\n" + index + "\n" + data);51 //--//MAIN\\--\\52 while (rawCode.length > 0) {53 var currentCharacter = rawCode.charCodeAt(0);54 switch (currentCharacter) {55 case 43: //+56 data[index]++;57 if (data[index] === 256) data[index] = 0;58 rawCode = rawCode.slice(1);59 break;60 case 45: //-61 data[index]--;62 if (data[index] === -1) data[index] = 255;63 rawCode = rawCode.slice(1);64 break;65 case 44: //,66 data[index] = rawInput.charCodeAt(0);67 rawInput = rawInput.slice(1);68 rawCode = rawCode.slice(1);69 break;70 case 46: //.71 output += String.fromCharCode(data[index]);72 rawCode = rawCode.slice(1);73 break;74 case 60: //<75 index--;76 if (index === -1) index = data.length - 1;77 rawCode = rawCode.slice(1);78 break;79 case 62: //>80 index++;81 if (index === data.length) index = 0;82 rawCode = rawCode.slice(1);83 break;84 case 91: //[85 var loopCode = loopedCode(rawCode);86 while (data[index] !== 0) {87 var newData = execute(loopCode, index, data, output);88 index = newData[0];89 data = newData[1];90 output = newData[2]91 }92 rawCode = rawCode.substring(loopCode.length + 2);93 break;94 default: //*95 rawCode = rawCode.slice(1);96 break;97 }98 }99 return [index, data, output];100 }101 if ($.url('?code')) {102 var inputCode = $.url('?code').replace(new RegExp('%3E', 'g'), '>').replace(new RegExp('%3C', 'g'), '<').replace(/%20/g, '');103 var inputInput = $.url('?input').replace(/%20/g, ' ') || "";104 $('#brainfuckCode').val(inputCode).trigger('propertychange');105 $('#brainfuckInput').val(inputInput).trigger('propertychange');106 $('#runButton').click();107 }...
babelPresetSweet.mjs
Source:babelPresetSweet.mjs
1import { expect } from 'chai';2import { transformAsync } from '@babel/core';3/* ç¼è¯ä»£ç */4async function transformCode(code, options) {5 return transformAsync(code, {6 presets: [7 [(await import('../lib/index.js')).default, options]8 ]9 });10}11async function transformCodeESM(code, options) {12 return transformAsync(code, {13 presets: [14 [(await import('../esm/index.js')).default, options]15 ]16 });17}18describe('babel-preset-sweet', function() {19 it('build javascript', async function() {20 const rawCode = `const a = 5;21 const b = <div />;22 const c = {};23 const d = c?.e;`24 const [{ code }, { code: codeESM }] = await Promise.all([25 transformCode(rawCode),26 transformCodeESM(rawCode)27 ]);28 expect(code.includes('var a = 5;')).to.be.true;29 expect(code.includes('jsx')).to.be.true;30 expect(code.includes('void 0') && code.includes('null')).to.be.true;31 expect(codeESM.includes('var a = 5;')).to.be.true;32 expect(codeESM.includes('jsx')).to.be.true;33 expect(codeESM.includes('void 0') && code.includes('null')).to.be.true;34 });35 it('build ecmascript', async function() {36 const rawCode = `const a = 5;37 async function func() {}`;38 const options = {39 env: { ecmascript: true }40 };41 const [{ code }, { code: codeESM }] = await Promise.all([42 transformCode(rawCode, options),43 transformCodeESM(rawCode, options)44 ]);45 expect(code.includes('const a = 5;')).to.be.true;46 expect(code.includes('async function')).to.be.true;47 expect(codeESM.includes('const a = 5;')).to.be.true;48 expect(codeESM.includes('async function')).to.be.true;49 });50 it('build typescript', async function() {51 const rawCode = 'const a: number = 5;';52 const options = {53 typescript: { use: true }54 };55 const [{ code }, { code: codeESM }] = await Promise.all([56 transformCode(rawCode, options),57 transformCodeESM(rawCode, options)58 ]);59 expect(code.includes('var a = 5;')).to.be.true;60 expect(codeESM.includes('var a = 5;')).to.be.true;61 });62 it('build transform-runtime', async function() {63 const rawCode = 'const isArray = Array.isArray([]);';64 const options = {65 env: { modules: 'commonjs' }66 };67 const [68 { code: code0 },69 { code: code1 },70 { code: code0ESM },71 { code: code1ESM }72 ] = await Promise.all([73 transformCode(rawCode),74 transformCode(rawCode, options),75 transformCodeESM(rawCode),76 transformCodeESM(rawCode, options)77 ]);78 expect(code0.includes('import')).to.be.true;79 expect(code1.includes('require')).to.be.true;80 expect(code0ESM.includes('import')).to.be.true;81 expect(code1ESM.includes('require')).to.be.true;82 });83 it('build polyfill', async function() {84 const rawCode = "globalThis.a = 5; 'Hello, world.'.replaceAll(/,/, ''); ";85 const options = {86 polyfill: true87 };88 const [{ code }, { code: codeESM }] = await Promise.all([89 transformCode(rawCode, options),90 transformCodeESM(rawCode, options)91 ]);92 expect(code.includes('globalthis')).to.be.true;93 expect(code.includes('string.prototype.replaceall')).to.be.true;94 expect(codeESM.includes('globalthis')).to.be.true;95 expect(codeESM.includes('string.prototype.replaceall')).to.be.true;96 });...
Using AI Code Generation
1bestCoder.rawCode("JavaScript");2bestCoder.rawCode("JavaScript");3bestCoder.rawCode("JavaScript");4bestCoder.rawCode("JavaScript");5bestCoder.rawCode("JavaScript");6bestCoder.rawCode("JavaScript");7bestCoder.rawCode("JavaScript");8bestCoder.rawCode("JavaScript");9bestCoder.rawCode("JavaScript");10bestCoder.rawCode("JavaScript");11bestCoder.rawCode("JavaScript");12bestCoder.rawCode("JavaScript");13bestCoder.rawCode("JavaScript");14bestCoder.rawCode("JavaScript");
Using AI Code Generation
1var bestCode = require('bestcode');2var code = bestCode.rawCode('var a = 10;');3console.log(code);4var bestCode = require('bestcode');5var code = bestCode.rawCode('var a = 10;');6console.log(code);7var bestCode = require('bestcode');8var code = bestCode.rawCode('var a = 10;');9console.log(code);10var bestCode = require('bestcode');11var code = bestCode.rawCode('var a = 10;');12console.log(code);13var bestCode = require('bestcode');14var code = bestCode.rawCode('var a = 10;');15console.log(code);16var bestCode = require('bestcode');17var code = bestCode.rawCode('var a = 10;');18console.log(code);19var bestCode = require('bestcode');20var code = bestCode.rawCode('var a = 10;');21console.log(code);22var bestCode = require('bestcode');23var code = bestCode.rawCode('var a = 10;');24console.log(code);25var bestCode = require('bestcode');26var code = bestCode.rawCode('var a = 10;');27console.log(code);28var bestCode = require('bestcode');
Using AI Code Generation
1const BestCoder = require('./BestCoder');2var coder = new BestCoder();3coder.rawCode('JavaScript');4class Person {5 constructor(firstName, lastName) {6 this.firstName = firstName;7 this.lastName = lastName;8 }9}10class Programmer extends Person {11 constructor(firstName, lastName, language) {12 super(firstName, lastName);13 this.language = language;14 }15}16const me = new Programmer('John', 'Doe', 'JavaScript');17console.log(me);18Programmer { firstName: 'John', lastName: 'Doe', language: 'JavaScript' }19const BestCoder = require('./BestCoder');20var coder = new BestCoder();21coder.rawCode('JavaScript');22import BestCoder from './BestCoder';23var coder = new BestCoder();24coder.rawCode('JavaScript');25const promise = new Promise((resolve, reject) => {26 setTimeout(() => {27 resolve('Resolved!');28 }, 2000);29});30promise.then((data) => {31 console.log(data);32});
Using AI Code Generation
1var BestPractice = require('./BestPractice.js');2var test = new BestPractice();3var testCode = "function test() { var x = 1; return x; }";4console.log(test.rawCode(testCode));5var esprima = require('esprima');6var escodegen = require('escodegen');7var _ = require('underscore');8function BestPractice() {9 this.rawCode = function(code) {10 try {11 esprima.parse(code);12 return true;13 } catch (e) {14 return false;15 }16 };17}18module.exports = BestPractice;
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!!