Best JavaScript code snippet using ava
helper.js
Source:helper.js
1var fs = require('fs');2var config = require(getFilePath('/lib/util/config'));3var getScopeFromString = function(string_to_search) {4 string_to_search = string_to_search.toLowerCase();5 for(var i = 0; i < config.data.scopes.length; i++) {6 if(string_to_search.includes(config.data.scopes[i].toLowerCase() + ' ')) {7 return config.data.scopes[i];8 }9 }10 return null;11}12module.exports.getScopeFromString = getScopeFromString;13var countStringMatches = function(string_to_find, string_to_search) {14 return(string_to_search.split(string_to_find).length - 1);15}16module.exports.countStringMatches = countStringMatches;17var parseTokens = function(model, tokens, commentList) {18 var inDescription = false;19 var token_obj;20 var token;21 var token_name;22 // Initialize token properties on the object23 for(var x = 0; x < tokens.length; x++) {24 var x_token_obj = tokens[x];25 var x_token = x_token_obj.name;26 var x_token_name = x_token.replace('@', '');27 if(x_token_obj['type'] == 'array') {28 if(!model[x_token_name]) {29 model[x_token_name] = [];30 }31 }32 else if(x_token_obj['type'] == 'array-typed') {33 if(!model[x_token_name]) {34 var token_model = x_token_obj['model'];35 if(typeof this[token_model] === 'undefined') {36 this[token_model] = require(getFilePath('/lib/models/' + token_model));37 }38 model[x_token_name] = null;39 }40 }41 else {42 model[x_token_name] = null;43 }44 }45 // Loop through comment lines looking for tokens46 for(var i = 0; i < commentList.length; i++) {47 var comment = commentList[i].trim();48 var token_start;49 var matchedToken = null;50 for(var x = 0; x < tokens.length; x++) {51 var x_token_obj = tokens[x];52 var x_token = x_token_obj.name;53 var x_token_name = x_token.replace('@', '');54 token_start = comment.toLowerCase().indexOf(x_token);55 if(token_start > -1) {56 token_obj = x_token_obj;57 token = x_token;58 token_name = x_token_name;59 comment = comment.replace('/**', '');60 comment = comment.replace('*/', '');61 comment = comment.replace('* ', '');62 comment = comment.replace('*', '');63 var comment_trimmed = comment.substring(token_start - 1 + token.length).trim();64 if(x_token_obj['type'] == 'array') {65 if(!model[token_name]) {66 model[token_name] = [];67 }68 model[token_name].push(comment_trimmed);69 }70 else if(x_token_obj['type'] == 'array-typed') {71 if(!model[token_name]) {72 var token_model = token_obj['model'];73 if(typeof this[token_model] === 'undefined') {74 this[token_model] = require(getFilePath('/lib/models/' + token_model));75 }76 model[token_name] = [];77 }78 model[token_name].push(new this[token_model](comment_trimmed));79 }80 else {81 model[token_name] = comment_trimmed;82 }83 inDescription = false;84 matchedToken = true;85 }86 }87 if(!matchedToken) {88 if(token == null) {89 token = '@description';90 token_name = 'description';91 }92 comment = comment.replace('/**', '');93 comment = comment.replace('*/', '');94 comment = comment.replace('* ', '');95 comment = comment.replace('*', '');96 if(token_obj && token_obj['type'] == 'array') {97 if(model[token_name][model[token_name.length - 1]]) {98 model[token_name][model[token_name.length - 1]] += comment.trim();99 }100 }101 else if(token_obj && token_obj['type'] == 'array-typed') {102 if(model[token_name][model[token_name].length - 1]) {103 model[token_name][model[token_name].length - 1].addLine(comment.trim());104 }105 }106 else if(token_obj && token_obj['type'] == 'single-raw') {107 if(!model[token_name]) {108 model[token_name] = '';109 }110 else {111 model[token_name] += '\n';112 }113 model[token_name] += comment;114 }115 else {116 comment = comment.trim();117 if(comment.length) {118 if(!model[token_name]) {119 model[token_name] = '';120 }121 else {122 model[token_name] += ' ';123 }124 model[token_name] += comment;125 }126 }127 }128 }129}130module.exports.parseTokens = parseTokens;131var trimForComments = function(string_to_trim) {132 // Check to see if we have a single line comment133 var comment_index = string_to_trim.indexOf('//');134 // If we do, take only the part of the line before it135 if(comment_index > -1) {136 string_to_trim = string_to_trim.substring(0, comment_index);137 }138 return string_to_trim;139}140module.exports.trimForComments = trimForComments;141var getPreviousWord = function(str, index) {142 var result;143 if(str && str.length > index) {144 var index_f;145 var index_l;146 for(index_f = index - 1, index_l = 0; index_f >= 0; index_f--) {147 if(index_l == 0) {148 if(str.charAt(index_f) == ' ') {149 continue;150 }151 index_l = index_f + 1;152 }153 else if(str.charAt(index_f) == ' ') {154 index_f++;155 break;156 }157 }158 if(index_f >= 0) {159 result = str.substring(index_f, index_l);160 }161 }162 return result;163}164module.exports.getPreviousWord = getPreviousWord;165var copyFile = function(source, target, cb) {166 console.log('* Copying file ' + source + ' to ' + target);167 var cbCalled = false;168 var rd = fs.createReadStream(source);169 rd.on("error", function(err) {170 done(err);171 });172 var wr = fs.createWriteStream(target);173 wr.on("error", function(err) {174 done(err);175 });176 wr.on("close", function(ex) {177 done();178 });179 rd.pipe(wr);180 function done(err) {181 if(err) {182 throw err;183 }184 if(!cbCalled && typeof cb !== 'undefined') {185 cb(err);186 cbCalled = true;187 }188 }189}190module.exports.copyFile = copyFile;191var deleteFolderRecursive = function(path) {192 if(fs.existsSync(path)) {193 fs.readdirSync(path).forEach(function(file, index) {194 var curPath = path + "/" + file;195 if(fs.lstatSync(curPath).isDirectory()) { // recurse196 deleteFolderRecursive(curPath);197 }198 else { // delete file199 fs.unlinkSync(curPath);200 }201 });202 fs.rmdirSync(path);203 }204};205var refreshFolder = function(path) {206 if(fs.existsSync(path + 'index.html')) {207 deleteFolderRecursive(path);208 fs.mkdirSync(path);209 }210 else {211 console.log('* Not clearing your docs directory since no index.html was found.');212 }213}...
parser.js
Source:parser.js
...67 }68 continue;69 }70 // keep track of our nesting so we can track our class71 var openBraceCount = helper.countStringMatches('{', file_data_line);72 var closeBraceCount = helper.countStringMatches('}', file_data_line);73 nestedBraceDepth += openBraceCount;74 nestedBraceDepth -= closeBraceCount;75 // if we are in a nested class, and we just got back to nesting level 1,76 // then we are done with the nested class, and should set its props and methods.77 if(nestedBraceDepth == 1 && openBraceCount != closeBraceCount && classModelStack.length > 1 && classModel != null) {78 classModelStack.pop();79 classModel = classModelStack.peek();80 }81 // Ignore anything after assignment82 var ich = file_data_line.indexOf('=');83 if(ich > -1) {84 file_data_line = file_data_line.substring(0, ich);85 }86 // ignore anything after {...
corrupt.js
Source:corrupt.js
...5import {withTemporaryFixture} from '../helpers/with-temporary-fixture.js';6function countMatches(string, regex) {7 return [...string.matchAll(regex)].length;8}9function countStringMatches(string, patternString) {10 if (patternString.length === 0) {11 throw new RangeError('Pattern must be non-empty');12 }13 let index = string.indexOf(patternString);14 let matches = 0;15 while (index !== -1 && index < string.length) {16 matches++;17 index = string.indexOf(patternString, index + patternString.length);18 }19 return matches;20}21test('snapshot corruption is reported to the console', async t => {22 await withTemporaryFixture(cwd('corrupt'), async cwd => {23 const snapPath = path.join(cwd, 'test.js.snap');24 await fs.writeFile(snapPath, Uint8Array.of(0x00));25 const result = await t.throwsAsync(fixture([], {cwd}));26 t.snapshot(result.stats.failed, 'failed tests');27 t.is(countMatches(result.stdout, /The snapshot file is corrupted./g), 2);28 t.is(countMatches(result.stdout, /File path:/g), 2);29 t.is(30 countMatches(31 result.stdout,32 /Please run AVA again with the .*--update-snapshots.* flag to recreate it\./g,33 ),34 2,35 );36 t.is(countStringMatches(result.stdout, snapPath), 2);37 });38});39test('with --update-snapshots, corrupt snapshot files are overwritten', async t => {40 await withTemporaryFixture(cwd('corrupt'), async cwd => {41 const snapPath = path.join(cwd, 'test.js.snap');42 const env = {43 AVA_FORCE_CI: 'not-ci',44 };45 await fs.writeFile(snapPath, Uint8Array.of(0x00));46 await fixture(['--update-snapshots'], {cwd, env});47 const snapContents = await fs.readFile(snapPath);48 t.not(snapContents.length, 1);49 });50});
Using AI Code Generation
1const availableFunctions = require('./availableFunctions.js');2const countStringMatches = availableFunctions.countStringMatches;3const string = 'The quick brown fox jumps over the lazy dog';4const subString = 'the';5console.log(countStringMatches(string, subString));6const countStringMatches = (string, subString) => {7 const regex = new RegExp(subString, 'gi');8 const matches = string.match(regex);9 return matches ? matches.length : 0;10};11module.exports = { countStringMatches };12const availableFunctions = require('./availableFunctions.js');13const countStringMatches = availableFunctions.countStringMatches;14const string = 'The quick brown fox jumps over the lazy dog';15const subString = 'the';16console.log(countStringMatches(string, subString));17const countStringMatches = (string, subString) => {18 const regex = new RegExp(subString, 'gi');19 const matches = string.match(regex);20 return matches ? matches.length : 0;21};22module.exports = { countStringMatches };23const availableFunctions = require('./availableFunctions.js');24const countStringMatches = availableFunctions.countStringMatches;25const string = 'The quick brown fox jumps over the lazy dog';26const subString = 'the';27console.log(countStringMatches(string, subString));28const countStringMatches = (string, subString) => {29 const regex = new RegExp(subString, 'gi');30 const matches = string.match(regex);31 return matches ? matches.length : 0;32};33module.exports = { countStringMatches };34const availableFunctions = require('./availableFunctions.js');35const countStringMatches = availableFunctions.countStringMatches;36const string = 'The quick brown fox jumps over the lazy dog';37const subString = 'the';38console.log(countStringMatches(string, subString));39const countStringMatches = (string, subString)
Using AI Code Generation
1const availableFunctions = require('./availableFunctions.js');2module.exports = {3 countStringMatches: function countStringMatches(str, char) {4 let count = 0;5 for (let i = 0; i < str.length; i++) {6 if (str[i] === char) {7 count++;8 }9 }10 return count;11 }12};
Using AI Code Generation
1const availableStringMethods = require('./stringMethods');2const { countStringMatches } = availableStringMethods;3const result = countStringMatches('This is a test string', 'is');4exports.countStringMatches = (string, substring, caseSensitive = false) => {5 let count = 0;6 if (caseSensitive) {7 string = string.toLowerCase();8 substring = substring.toLowerCase();9 }10 let index = string.indexOf(substring);11 while (index !== -1) {12 count++;13 index = string.indexOf(substring, index + 1);14 }15 return count;16};
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!!