Best JavaScript code snippet using mocha
generate-defs.js
Source:generate-defs.js
...10function printf() {11 out.write(format.apply(format, arguments), 'utf8');12}13function nl() { out.write('\n'); }14function println() { printf.apply(printf, arguments); nl(); }15function isEmptyObject(val) {16 return (val != null && typeof val === 'object' &&17 Object.keys(val).length === 0);18}19function stringifyValue(val) {20 return (isEmptyObject(val)) ? 'EMPTY_OBJECT' :21 JSON.stringify(val);22}23var constants = {};24var constant_strs = {};25for (var i = 0, len = defs.constants.length; i < len; i++) {26 var cdef = defs.constants[i];27 constants[constantName(cdef)] = cdef.value;28 constant_strs[cdef.value] = cdef.name;29}30function constantName(def) {31 return def.name.replace(/-/g, '_');32}33function methodName(clazz, method) {34 return initial(clazz.name) + method.name.split('-').map(initial).join('');35}36function propertyName(dashed) {37 var parts = dashed.split('-');38 return parts[0] + parts.slice(1).map(initial).join('');39}40function initial(part) {41 return part.charAt(0).toUpperCase() + part.substr(1);42}43function argument(a) {44 var type = a.type || domains[a.domain];45 var friendlyName = propertyName(a.name);46 return {type: type, name: friendlyName, default: a['default-value']};47}48var domains = {};49for (var i=0, len = defs.domains.length; i < len; i++) {50 var dom = defs.domains[i];51 domains[dom[0]] = dom[1];52}53var methods = {};54var propertieses = {};55for (var i = 0, len = defs.classes.length; i < len; i++) {56 var clazz = defs.classes[i];57 for (var j = 0, num = clazz.methods.length; j < num; j++) {58 var method = clazz.methods[j];59 var name = methodName(clazz, method);60 var info = 'methodInfo' + name;61 methods[name] = {62 id: methodId(clazz, method),63 name: name,64 methodId: method.id,65 clazzId: clazz.id,66 clazz: clazz.name,67 args: method['arguments'].map(argument),68 isReply: method.answer,69 encoder: 'encode' + name,70 decoder: 'decode' + name,71 info: info72 };73 }74 if (clazz.properties && clazz.properties.length > 0) {75 var name = propertiesName(clazz);76 var props = clazz.properties;77 propertieses[name] = {78 id: clazz.id,79 name: name,80 encoder: 'encode' + name,81 decoder: 'decode' + name,82 info: 'propertiesInfo' + name,83 args: props.map(argument),84 };85 }86}87// OK let's get emitting88println(89'/** @preserve This file is generated by the script\n',90'* ../bin/generate-defs.js, which is not in general included in a\n',91'* distribution, but is available in the source repository e.g. at\n',92'* https://github.com/squaremo/amqp.node/\n',93'*/');94println("'use strict';"); nl();95println('var Buffer = require("safe-buffer").Buffer;');96nl()97println('var codec = require("./codec");');98println('var ints = require("buffer-more-ints");');99println('var encodeTable = codec.encodeTable;');100println('var decodeFields = codec.decodeFields;');101nl();102println('var SCRATCH = Buffer.alloc(65536);');103println('var EMPTY_OBJECT = Object.freeze({});');104println('module.exports.constants = %s',105 JSON.stringify(constants));106nl();107println('module.exports.constant_strs = %s',108 JSON.stringify(constant_strs));109nl();110println('module.exports.FRAME_OVERHEAD = %d;', FRAME_OVERHEAD);111nl();112println('module.exports.decode = function(id, buf) {');113println('switch (id) {');114for (var m in methods) {115 var method = methods[m];116 println('case %d: return %s(buf);', method.id, method.decoder);117}118for (var p in propertieses) {119 var props = propertieses[p];120 println('case %d: return %s(buf);', props.id, props.decoder);121}122println('default: throw new Error("Unknown class/method ID");');123println('}}'); nl();124println('module.exports.encodeMethod =',125 'function(id, channel, fields) {');126println('switch (id) {');127for (var m in methods) {128 var method = methods[m];129 println('case %d: return %s(channel, fields);',130 method.id, method.encoder);131}132println('default: throw new Error("Unknown class/method ID");');133println('}}'); nl();134println('module.exports.encodeProperties ='135 , 'function(id, channel, size, fields) {');136println('switch (id) {');137for (var p in propertieses) {138 var props = propertieses[p];139 println('case %d: return %s(channel, size, fields);',140 props.id, props.encoder);141}142println('default: throw new Error("Unknown class/properties ID");');143println('}}'); nl();144println('module.exports.info = function(id) {');145println('switch(id) {');146for (var m in methods) {147 var method = methods[m];148 println('case %d: return %s; ', method.id, method.info);149}150for (var p in propertieses) {151 var properties = propertieses[p];152 println('case %d: return %s', properties.id, properties.info);153}154println('default: throw new Error("Unknown class/method ID");');155println('}}'); nl();156for (var m in methods) {157 var method = methods[m];158 println('module.exports.%s = %d;', m, method.id);159 decoderFn(method); nl();160 encoderFn(method); nl();161 infoObj(method); nl();162}163for (var p in propertieses) {164 var properties = propertieses[p];165 println('module.exports.%s = %d;', p, properties.id);166 encodePropsFn(properties); nl();167 decodePropsFn(properties); nl();168 infoObj(properties); nl();169}170function methodId(clazz, method) {171 return (clazz.id << 16) + method.id;172}173function propertiesName(clazz) {174 return initial(clazz.name) + 'Properties';175}176function valTypeTest(arg) {177 switch (arg.type) {178 // everything is booleany179 case 'bit': return 'true'180 case 'octet':181 case 'short':182 case 'long':183 case 'longlong':184 case 'timestamp': return "typeof val === 'number' && !isNaN(val)";185 case 'shortstr': return "typeof val === 'string' &&" +186 " Buffer.byteLength(val) < 256";187 case 'longstr': return "Buffer.isBuffer(val)";188 case 'table': return "typeof val === 'object'";189 }190}191function typeDesc(t) {192 switch (t) {193 case 'bit': return 'booleany';194 case 'octet':195 case 'short':196 case 'long':197 case 'longlong':198 case 'timestamp': return "a number (but not NaN)";199 case 'shortstr': return "a string (up to 255 chars)";200 case 'longstr': return "a Buffer";201 case 'table': return "an object";202 }203}204function defaultValueRepr(arg) {205 switch (arg.type) {206 case 'longstr':207 return format("Buffer.from(%s)", JSON.stringify(arg.default));208 default:209 // assumes no tables as defaults210 return JSON.stringify(arg.default);211 }212}213// Emit code to assign the arg value to `val`.214function assignArg(a) {215 println("val = fields['%s'];", a.name);216}217function assignOrDefault(a) {218 println("val = fields['%s'];", a.name);219 println("if (val === undefined) val = %s;", defaultValueRepr(a));220}221// Emit code for assigning an argument value to `val`, checking that222// it exists (if it does not have a default) and is the correct223// type.224function checkAssignArg(a) {225 assignArg(a);226 println('if (val === undefined) {');227 if (a.default !== undefined) {228 println('val = %s;', defaultValueRepr(a));229 }230 else {231 println('throw new Error("Missing value for mandatory field \'%s\'");', a.name);232 }233 println('}'); // undefined test234 println('else if (!(%s)) {', valTypeTest(a));235 println('throw new TypeError(');236 println('"Field \'%s\' is the wrong type; must be %s");',237 a.name, typeDesc(a.type));238 println('}'); // type test239}240// Emit code for encoding `val` as a table and assign to a fresh241// variable (based on the arg name). I use a scratch buffer to compose242// the encoded table, otherwise I'd have to do a size calculation pass243// first. I can get away with this only because 1. the encoding244// procedures are not re-entrant; and, 2. I copy the result into245// another buffer before returning. `scratchOffset`, `val`, `len` are246// expected to have been declared.247function assignTable(a) {248 var varname = tableVar(a);249 println(250 "len = encodeTable(SCRATCH, val, scratchOffset);");251 println('var %s = SCRATCH.slice(scratchOffset, scratchOffset + len);', varname);252 println('scratchOffset += len;');253}254function tableVar(a) {255 return a.name + '_encoded';256}257function stringLenVar(a) {258 return a.name + '_len';259}260function assignStringLen(a) {261 var v = stringLenVar(a);262 // Assumes the value or default is in val263 println("var %s = Buffer.byteLength(val, 'utf8');", v);264}265function encoderFn(method) {266 var args = method['args'];267 println('function %s(channel, fields) {', method.encoder);268 println('var offset = 0, val = null, bits = 0, varyingSize = 0;');269 println('var len, scratchOffset = 0;');270 // Encoding is split into two parts. Some fields have a fixed size271 // (e.g., integers of a specific width), while some have a size that272 // depends on the datum (e.g., strings). Each field will therefore273 // either 1. contribute to the fixed size; or 2. emit code to274 // calculate the size (and possibly the encoded value, in the case275 // of tables).276 var fixedSize = METHOD_OVERHEAD;277 var bitsInARow = 0;278 for (var i=0, len = args.length; i < len; i++) {279 var arg = args[i];280 if (arg.type != 'bit') bitsInARow = 0;281 switch (arg.type) {282 // varying size283 case 'shortstr':284 checkAssignArg(arg);285 assignStringLen(arg);286 println("varyingSize += %s;", stringLenVar(arg));287 fixedSize += 1;288 break;289 case 'longstr':290 checkAssignArg(arg);291 println("varyingSize += val.length;");292 fixedSize += 4;293 break;294 case 'table':295 // For a table we have to encode the table before we can see its296 // length.297 checkAssignArg(arg);298 assignTable(arg);299 println('varyingSize += %s.length;', tableVar(arg));300 break;301 // fixed size302 case 'octet': fixedSize += 1; break;303 case 'short': fixedSize += 2; break;304 case 'long': fixedSize += 4; break;305 case 'longlong': //fall through306 case 'timestamp':307 fixedSize += 8; break;308 case 'bit':309 bitsInARow ++;310 // open a fresh pack o' bits311 if (bitsInARow === 1) fixedSize += 1;312 // just used a pack; reset313 else if (bitsInARow === 8) bitsInARow = 0;314 break;315 }316 }317 println('var buffer = Buffer.alloc(%d + varyingSize);', fixedSize);318 println('buffer[0] = %d;', constants.FRAME_METHOD);319 println('buffer.writeUInt16BE(channel, 1);');320 // skip size for now, we'll write it in when we know321 println('buffer.writeUInt32BE(%d, 7);', method.id);322 println('offset = 11;');323 bitsInARow = 0;324 for (var i = 0, len = args.length; i < len; i++) {325 var a = args[i];326 // Flush any collected bits before doing a new field327 if (a.type != 'bit' && bitsInARow > 0) {328 bitsInARow = 0;329 println('buffer[offset] = bits; offset++; bits = 0;');330 }331 switch (a.type) {332 case 'octet':333 checkAssignArg(a);334 println('buffer.writeUInt8(val, offset); offset++;');335 break;336 case 'short':337 checkAssignArg(a);338 println('buffer.writeUInt16BE(val, offset); offset += 2;');339 break;340 case 'long':341 checkAssignArg(a);342 println('buffer.writeUInt32BE(val, offset); offset += 4;');343 break;344 case 'longlong':345 case 'timestamp':346 checkAssignArg(a);347 println('ints.writeUInt64BE(buffer, val, offset); offset += 8;');348 break;349 case 'bit':350 checkAssignArg(a);351 println('if (val) bits += %d;', 1 << bitsInARow);352 if (bitsInARow === 7) { // I don't think this ever happens, but whatever353 println('buffer[offset] = bits; offset++; bits = 0;');354 bitsInARow = 0;355 }356 else bitsInARow++;357 break;358 case 'shortstr':359 assignOrDefault(a);360 println('buffer[offset] = %s; offset++;', stringLenVar(a));361 println('buffer.write(val, offset, "utf8"); offset += %s;',362 stringLenVar(a));363 break;364 case 'longstr':365 assignOrDefault(a);366 println('len = val.length;');367 println('buffer.writeUInt32BE(len, offset); offset += 4;');368 println('val.copy(buffer, offset); offset += len;');369 break;370 case 'table':371 println('offset += %s.copy(buffer, offset);', tableVar(a));372 break;373 default: throw new Error("Unexpected argument type: " + a.type);374 }375 }376 // Flush any collected bits at the end377 if (bitsInARow > 0) {378 println('buffer[offset] = bits; offset++;');379 }380 println('buffer[offset] = %d;', constants.FRAME_END);381 // size does not include the frame header or frame end byte382 println('buffer.writeUInt32BE(offset - 7, 3);');383 println('return buffer;');384 println('}');385}386function fieldsDecl(args) {387 println('var fields = {');388 for (var i=0, num=args.length; i < num; i++) {389 println('%s: undefined,', args[i].name);390 }391 println('};');392}393function decoderFn(method) {394 var args = method.args;395 println('function %s(buffer) {', method.decoder);396 println('var offset = 0, val, len;');397 fieldsDecl(args);398 var bitsInARow = 0;399 for (var i=0, num=args.length; i < num; i++) {400 var a = args[i];401 var field = "fields['" + a.name + "']";402 // Flush any collected bits before doing a new field403 if (a.type != 'bit' && bitsInARow > 0) {404 bitsInARow = 0;405 println('offset++;');406 }407 switch (a.type) {408 case 'octet':409 println('val = buffer[offset]; offset++;');410 break;411 case 'short':412 println('val = buffer.readUInt16BE(offset); offset += 2;');413 break;414 case 'long':415 println('val = buffer.readUInt32BE(offset); offset += 4;');416 break;417 case 'longlong':418 case 'timestamp':419 println('val = ints.readUInt64BE(buffer, offset); offset += 8;');420 break;421 case 'bit':422 var bit = 1 << bitsInARow;423 println('val = !!(buffer[offset] & %d);', bit);424 if (bitsInARow === 7) {425 println('offset++;');426 bitsInARow = 0;427 }428 else bitsInARow++;429 break;430 case 'longstr':431 println('len = buffer.readUInt32BE(offset); offset += 4;');432 println('val = buffer.slice(offset, offset + len);');433 println('offset += len;');434 break;435 case 'shortstr':436 println('len = buffer.readUInt8(offset); offset++;');437 println('val = buffer.toString("utf8", offset, offset + len);');438 println('offset += len;');439 break;440 case 'table':441 println('len = buffer.readUInt32BE(offset); offset += 4;');442 println('val = decodeFields(buffer.slice(offset, offset + len));');443 println('offset += len;');444 break;445 default:446 throw new TypeError("Unexpected type in argument list: " + a.type);447 }448 println('%s = val;', field);449 }450 println('return fields;');451 println('}');452}453function infoObj(thing) {454 var info = JSON.stringify({id: thing.id,455 classId: thing.clazzId,456 methodId: thing.methodId,457 name: thing.name,458 args: thing.args});459 println('var %s = module.exports.%s = %s;',460 thing.info, thing.info, info);461}462// The flags are laid out in groups of fifteen in a short (high to463// low bits), with a continuation bit (at 0) and another group464// following if there's more than fifteen. Presence and absence465// are conflated with true and false, for bit fields (i.e., if the466// flag for the field is set, it's true, otherwise false).467//468// However, none of that is actually used in AMQP 0-9-1. The only469// instance of properties -- basic properties -- has 14 fields, none470// of them bits.471function flagAt(index) {472 return 1 << (15 - index);473}474function encodePropsFn(props) {475 println('function %s(channel, size, fields) {', props.encoder);476 println('var offset = 0, flags = 0, val, len;');477 println('var scratchOffset = 0, varyingSize = 0;');478 var fixedSize = PROPERTIES_OVERHEAD;479 var args = props.args;480 function incVarying(by) {481 println("varyingSize += %d;", by);482 }483 for (var i=0, num=args.length; i < num; i++) {484 var p = args[i];485 assignArg(p);486 println("if (val != undefined) {");487 println("if (%s) {", valTypeTest(p));488 switch (p.type) {489 case 'shortstr':490 assignStringLen(p);491 incVarying(1);492 println('varyingSize += %s;', stringLenVar(p));493 break;494 case 'longstr':495 incVarying(4);496 println('varyingSize += val.length;');497 break;498 case 'table':499 assignTable(p);500 println('varyingSize += %s.length;', tableVar(p));501 break;502 case 'octet': incVarying(1); break;503 case 'short': incVarying(2); break;504 case 'long': incVarying(4); break;505 case 'longlong': // fall through506 case 'timestamp':507 incVarying(8); break;508 // no case for bit, as they are accounted for in the flags509 }510 println('} else {');511 println('throw new TypeError(');512 println('"Field \'%s\' is the wrong type; must be %s");',513 p.name, typeDesc(p.type));514 println('}');515 println('}');516 }517 println('var buffer = Buffer.alloc(%d + varyingSize);', fixedSize);518 println('buffer[0] = %d', constants.FRAME_HEADER);519 println('buffer.writeUInt16BE(channel, 1);');520 // content class ID and 'weight' (== 0)521 println('buffer.writeUInt32BE(%d, 7);', props.id << 16);522 // skip frame size for now, we'll write it in when we know.523 // body size524 println('ints.writeUInt64BE(buffer, size, 11);');525 println('flags = 0;');526 // we'll write the flags later too527 println('offset = 21;');528 for (var i=0, num=args.length; i < num; i++) {529 var p = args[i];530 var flag = flagAt(i);531 assignArg(p);532 println("if (val != undefined) {");533 if (p.type === 'bit') { // which none of them are ..534 println('if (val) flags += %d;', flag);535 }536 else {537 println('flags += %d;', flag);538 // %%% FIXME only slightly different to the method args encoding539 switch (p.type) {540 case 'octet':541 println('buffer.writeUInt8(val, offset); offset++;');542 break;543 case 'short':544 println('buffer.writeUInt16BE(val, offset); offset += 2;');545 break;546 case 'long':547 println('buffer.writeUInt32BE(val, offset); offset += 4;');548 break;549 case 'longlong':550 case 'timestamp':551 println('ints.writeUInt64BE(buffer, val, offset);');552 println('offset += 8;');553 break;554 case 'shortstr':555 var v = stringLenVar(p);556 println('buffer[offset] = %s; offset++;', v);557 println("buffer.write(val, offset, 'utf8');");558 println("offset += %s;", v);559 break;560 case 'longstr':561 println('buffer.writeUInt32BE(val.length, offset);');562 println('offset += 4;');563 println('offset += val.copy(buffer, offset);');564 break;565 case 'table':566 println('offset += %s.copy(buffer, offset);', tableVar(p));567 break;568 default: throw new Error("Unexpected argument type: " + p.type);569 }570 }571 println('}'); // != undefined572 }573 println('buffer[offset] = %d;', constants.FRAME_END);574 // size does not include the frame header or frame end byte575 println('buffer.writeUInt32BE(offset - 7, 3);');576 println('buffer.writeUInt16BE(flags, 19);');577 println('return buffer.slice(0, offset + 1);');578 println('}');579}580function decodePropsFn(props) {581 var args = props.args;582 println('function %s(buffer) {', props.decoder);583 println('var flags, offset = 2, val, len;');584 println('flags = buffer.readUInt16BE(0);');585 println('if (flags === 0) return {};');586 fieldsDecl(args);587 for (var i=0, num=args.length; i < num; i++) {588 var p = argument(args[i]);589 var field = "fields['" + p.name + "']";590 println('if (flags & %d) {', flagAt(i));591 if (p.type === 'bit') {592 println('%d = true;', field);593 }594 else {595 switch (p.type) {596 case 'octet':597 println('val = buffer[offset]; offset++;');598 break;599 case 'short':600 println('val = buffer.readUInt16BE(offset); offset += 2;');601 break;602 case 'long':603 println('val = buffer.readUInt32BE(offset); offset += 4;');604 break;605 case 'longlong':606 case 'timestamp':607 println('val = ints.readUInt64BE(buffer, offset); offset += 8;');608 break;609 case 'longstr':610 println('len = buffer.readUInt32BE(offset); offset += 4;');611 println('val = buffer.slice(offset, offset + len);');612 println('offset += len;');613 break;614 case 'shortstr':615 println('len = buffer.readUInt8(offset); offset++;');616 println('val = buffer.toString("utf8", offset, offset + len);');617 println('offset += len;');618 break;619 case 'table':620 println('len = buffer.readUInt32BE(offset); offset += 4;');621 println('val = decodeFields(buffer.slice(offset, offset + len));');622 println('offset += len;');623 break;624 default:625 throw new TypeError("Unexpected type in argument list: " + p.type);626 }627 println('%s = val;', field);628 }629 println('}');630 }631 println('return fields;');632 println('}');...
cobertura.js
Source:cobertura.js
...68 var metrics = node.metrics,69 branchByLine = branchCoverageByLine(fileCoverage),70 fnMap,71 lines;72 writer.println('\t\t<class' +73 attr('name', asClassName(node)) +74 attr('filename', node.fullPath()) +75 attr('line-rate', metrics.lines.pct / 100.0) +76 attr('branch-rate', metrics.branches.pct / 100.0) +77 '>');78 writer.println('\t\t<methods>');79 fnMap = fileCoverage.fnMap;80 Object.keys(fnMap).forEach(function (k) {81 var name = fnMap[k].name,82 hits = fileCoverage.f[k];83 writer.println(84 '\t\t\t<method' +85 attr('name', name) +86 attr('hits', hits) +87 attr('signature', '()V') + //fake out a no-args void return88 '>'89 );90 //Add the function definition line and hits so that jenkins cobertura plugin records method hits91 writer.println(92 '\t\t\t\t<lines>' +93 '<line' +94 attr('number', fnMap[k].line) +95 attr('hits', fileCoverage.f[k]) +96 '/>' +97 '</lines>'98 );99 writer.println('\t\t\t</method>');100 });101 writer.println('\t\t</methods>');102 writer.println('\t\t<lines>');103 lines = fileCoverage.l;104 Object.keys(lines).forEach(function (k) {105 var str = '\t\t\t<line' +106 attr('number', k) +107 attr('hits', lines[k]),108 branchDetail = branchByLine[k];109 if (!branchDetail) {110 str += attr('branch', false);111 } else {112 str += attr('branch', true) +113 attr('condition-coverage', branchDetail.coverage +114 '% (' + branchDetail.covered + '/' + branchDetail.total + ')');115 }116 writer.println(str + '/>');117 });118 writer.println('\t\t</lines>');119 writer.println('\t\t</class>');120}121function walk(node, collector, writer, level) {122 var metrics;123 if (level === 0) {124 metrics = node.metrics;125 writer.println('<?xml version="1.0" ?>');126 writer.println('<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">');127 writer.println('<coverage' +128 attr('lines-valid', metrics.lines.total) +129 attr('lines-covered', metrics.lines.covered) +130 attr('line-rate', metrics.lines.pct / 100.0) +131 attr('branches-valid', metrics.branches.total) +132 attr('branches-covered', metrics.branches.covered) +133 attr('branch-rate', metrics.branches.pct / 100.0) +134 attr('timestamp', Date.now()) +135 'complexity="0" version="0.1">');136 writer.println('<sources />');137 writer.println('<packages>');138 }139 if (node.packageMetrics) {140 metrics = node.packageMetrics;141 writer.println('\t<package' +142 attr('name', asJavaPackage(node)) +143 attr('line-rate', metrics.lines.pct / 100.0) +144 attr('branch-rate', metrics.branches.pct / 100.0) +145 '>');146 writer.println('\t<classes>');147 node.children.filter(function (child) { return child.kind !== 'dir'; }).148 forEach(function (child) {149 addClassStats(child, collector.fileCoverageFor(child.fullPath()), writer);150 });151 writer.println('\t</classes>');152 writer.println('\t</package>');153 }154 node.children.filter(function (child) { return child.kind === 'dir'; }).155 forEach(function (child) {156 walk(child, collector, writer, level + 1);157 });158 if (level === 0) {159 writer.println('</packages>');160 writer.println('</coverage>');161 }162}163Report.mix(CoberturaReport, {164 writeReport: function (collector, sync) {165 var summarizer = new TreeSummarizer(),166 outputFile = path.join(this.dir, this.file),167 writer = this.opts.writer || new FileWriter(sync),168 tree,169 root;170 collector.files().forEach(function (key) {171 summarizer.addFileCoverageSummary(key, utils.summarizeFileCoverage(collector.fileCoverageFor(key)));172 });173 tree = summarizer.getTreeSummary();174 root = tree.root;...
2_1_objects.js
Source:2_1_objects.js
...10point["y"] = 20;11dumpObject("modified point", point);12point = {"x": 100, "z": 200};13dumpObject("point with default values", point);14println();15println("Undefined property: " + point.qqq + " === " + point['qqq']);16println();17const strangeObject = {18 "hello world": "zzz",19 1: "qqq"20};21strangeObject["1 2"] = false;22dumpObject("strangeObject", strangeObject);23example('strangeObject[1] === strangeObject["1"]', "keys are strings");24example('point["x"] === point.x && point["y"] === point.y', "shorthand syntax");25println();26section("Properties testing");27example("'x' in point", " point has property 'x'");28example("'a' in point", " point has property 'a'");29println();30section("Properties dumping");31for (let property in point) {32 println(" point['" + property + "'] = " + point[property]);33}34section("Inheritance");35point = {x: 10, y: 20};36let shiftedPoint = Object.create(point);37shiftedPoint.dx = 1;38shiftedPoint.dy = 2;39dumpObject("point", point);40dumpObject("shiftedPoint", shiftedPoint);41println();42println("point is prototype of shiftedPoint: " + (Object.getPrototypeOf(shiftedPoint) === point));43println();44shiftedPoint.dx = -1;45dumpObject("shiftedPoint with modified dx", shiftedPoint);46println();47shiftedPoint.x = 1;48dumpObject("shiftedPoint with modified x", shiftedPoint);49dumpObject("point remains intact", point);50println();51point.y = 1000;52dumpObject("point with modified y", point);53dumpObject("shiftedPoint with propagated y", shiftedPoint);54println();55point.x = 1000;56dumpObject("point with modified x", point);57dumpObject("shiftedPoint without propagated x", shiftedPoint);58println();59delete shiftedPoint.x;60dumpObject("shiftedPoint with deleted local x", shiftedPoint);61println();62section("Methods");63point = {64 x: 10,65 y: 20,66 getX: function() { return point.x; },67 getY: function() { return point.y; }68};69dumpObject("Functions in properties: point", point);70println("Result of call to getX: " + point.getX());71println("Actual value of getX: " + point.getX);72println();73shiftedPoint = Object.create(point);74shiftedPoint.dx = 1;75shiftedPoint.dy = 2;76shiftedPoint.getX = function() { return shiftedPoint.x + shiftedPoint.dx; };77shiftedPoint.getY = function() { return shiftedPoint.y + shiftedPoint.dy; };78dumpObject("Functions in properties: shiftedPoint", shiftedPoint);79println();80println("Aliasing problem");81let point2 = point;82dumpObject("point2 references to the same object as point", point2);83point = {x: -1, y: -2};84dumpObject("point references new object", point);85dumpObject("point2 has correct x and y, but strange getX() and getY()", point2);86println("point2.getX takes value from point, not from point2: " + point2.getX);87println();88point = {89 x: 10,90 y: 20,91 getX: function() { return this.x; },92 getY: function() { return this.y; }93};94point2 = point;95point = {x: -1, y: -2};96println("'this' -- the object, method in called on");97dumpObject("point", point);98dumpObject("methods of point2 references correct object", point2);99println("dot-notations is shorthand for array-notation: " + point2.getX() + " === " + point2["getX"]());100println();101println("Specifying context object in apply: " +102 point2.getX.apply(point, ["other arguments"]) + ", " +103 point2.getX.apply(point2, ["other arguments"])104);105println("Specifying context object in call: " +106 point2.getX.call(point, "other arguments") + ", " +107 point2.getX.call(point2, "other arguments")108);109section("Constructors");110function pointFactory(x, y) {111 const point = {};112 point.x = x;113 point.y = y;114 point.getX = function() { return this.x; };115 point.getY = function() { return this.y; };116 return point;117}118dumpObject("point produced by factory", pointFactory(10, 20));119println();120function Point(x, y) {121// const point = {};122 this.x = x;123 this.y = y;124 this.getX = function() { return this.x; };125 this.getY = function() { return this.y; };126// return point;127}128dumpObject("point created by constructor", new Point(10, 20));129println("Constructor is ordinary function: " + (typeof Point) + "\n" + Point);130println();131function PointWithPrototype(x, y) {132 this.x = x;133 this.y = y;134}135PointWithPrototype.prototype.getX = function() { return this.x; };136PointWithPrototype.prototype.getY = function() { return this.y; };137dumpObject("PointWithPrototype.prototype", PointWithPrototype.prototype);138dumpObject("point created by constructor with prototype", new PointWithPrototype(10, 20));139println();140point = Object.create(PointWithPrototype.prototype);141PointWithPrototype.call(point, 1, 2);142dumpObject("PointWithPrototype created without new", point);...
abbreviations5.js
Source:abbreviations5.js
...33}34// katescript header35const println = console.log;36const abbrKeys = Object.keys(abbrs)37println('var katescript = {')38println(' "author": "Jonathan Poelen <jonathan.poelen+katescript@gmail.com>",')39println(' "license": "BSD",')40println(' "revision": ' + revision + ',')41println(' "kate-version": "5.1",')42println(' "functions": ["' + abbrKeys.join('", "') + '"],')43println(' "actions": [')44println(abbrKeys.map((k) => ` {"function": "${k}", "category": "${cat}", "interactive": false, "name": ${abbrDesc(abbrs[k])}, "shortcut": "${abbrs[k].shortcut}"}`).join(',\n'))45println(' ]')46println("};\n")47// make functions48println("require('cursor.js')\n")49for (const k in abbrs)50{51 println('function ' + k + '() {')52 const abbr = abbrs[k]53 const t = abbr.text54 const addLine = (abbr.addLine !== -1) ? '+document.line(c.line).trim()+\''+t.substring(abbr.addLine)+'\'' : ''55 const tline = (abbr.addLine !== -1) ? "'" + t.substring(0, abbr.addLine) + "'" + addLine : ''56 if (!abbr.pos && abbr.text[0] != ' ')57 {58 if (abbr.addLine !== -1)59 {60 println(' const c = view.cursorPosition();')61 println(' document.insertText(c, ' + tline + ')')62 }63 else64 {65 println(' document.insertText(view.cursorPosition(), \'' + t + '\')')66 }67 }68 else69 {70 println(' const c = view.cursorPosition();')71 if (abbr.text[0] != ' ')72 {73 if (abbr.addLine !== -1)74 {75 println(' const t = ' + tline)76 println(' document.insertText(c, t)')77 }78 else79 {80 println(' document.insertText(c, \'' + t + '\')')81 }82 }83 else84 {85 const cond = "document.charAt(c) == ' ' ? '" + t.substring(1) + "' : '" + t + "'"86 if (abbr.addLine !== -1)87 {88 cond = '(' + cond + ')' + addLine + "'" + suffix + "'"89 }90 println(abbr.pos91 ? ' const t = ' + cond + '\n' +92 ' document.insertText(c, t)'93 : ' document.insertText(c, ' + cond + ')'94 )95 }96 if (abbr.pos)97 {98 println(' c.column += ' + (abbr.text[0] == ' ' || abbr.addLine !== -1 ? 't.length - ' + -abbr.pos : t.length + abbr.pos))99 println(' view.setCursorPosition(c)')100 }101 }102 println("}\n")103}104// make help function105println('function help(cmd) {')106for (const k in abbrs)107{108 println(` if (cmd === '${k}') return i18n('insert "${abbrs[k].text}"')`)109}...
index.js
Source:index.js
...18 const lines = fc.getLineCoverage();19 const branches = fc.b;20 const branchMap = fc.branchMap;21 const summary = node.getCoverageSummary();22 writer.println('TN:'); //no test name23 writer.println('SF:' + fc.path);24 Object.keys(functionMap).forEach(key => {25 const meta = functionMap[key];26 writer.println('FN:' + [meta.decl.start.line, meta.name].join(','));27 });28 writer.println('FNF:' + summary.functions.total);29 writer.println('FNH:' + summary.functions.covered);30 Object.keys(functionMap).forEach(key => {31 const stats = functions[key];32 const meta = functionMap[key];33 writer.println('FNDA:' + [stats, meta.name].join(','));34 });35 Object.keys(lines).forEach(key => {36 const stat = lines[key];37 writer.println('DA:' + [key, stat].join(','));38 });39 writer.println('LF:' + summary.lines.total);40 writer.println('LH:' + summary.lines.covered);41 Object.keys(branches).forEach(key => {42 const branchArray = branches[key];43 const meta = branchMap[key];44 const line = meta.loc.start.line;45 let i = 0;46 branchArray.forEach(b => {47 writer.println('BRDA:' + [line, key, i, b].join(','));48 i += 1;49 });50 });51 writer.println('BRF:' + summary.branches.total);52 writer.println('BRH:' + summary.branches.covered);53 writer.println('end_of_record');54};55LcovOnlyReport.prototype.onEnd = function() {56 this.contentWriter.close();57};...
logic-gates.js
Source:logic-gates.js
1println('|-------------------------------------------- |');2println('| Welcome to the Logical Processing Simulator |');3println('| Choose a Logical Gate to Simulate |');4println('|-------------------------------------------- |');5println('\n');6println('|-----------------------------------------------------|');7println('| 1. AND Gate 2. NAND Gate 3. OR Gate 4. NOR Gate |');8println('| 5. EX-OR Gate 6. EX-NOR Gatev7. INVERTER 8. BUFFER |');9println('|-----------------------------------------------------|');10println('\n');11var gate = readLine('Choose the gat you want to test: ');12println('\n');13println('\n');14if (gate == '1'){15 println('|----------|');16 println('| AND Gate |');17 println('|----------|');18 19 println('\n');20 21 var in_a = readLine('Input A (use 1 or 0): ');22 var in_b = readLine('Input B (use 1 or 0): ');23 24 println('\n');25 26 println('In A: ' + in_a);27 println('In B: ' + in_b);28 29 println('\n');30 31 if (in_a == '1' && in_b == '1'){32 println('Out: 1');33 }else{34 println('Out: 0');35 }36}else if (gate == '2'){37 println('|-----------|');38 println('| NAND Gate |');39 println('|-----------|');40 41 println('\n');42 43 var in_a = readLine('Input A (use 1 or 0): ');44 var in_b = readLine('Input B (use 1 or 0): ');45 46 println('\n');47 48 println('In A: ' + in_a);49 println('In B: ' + in_b);50 51 println('\n');52 53 if (in_a == '1' && in_b == '1'){54 println('Out: 0');55 }else{56 println('Out: 1');57 }58}else if (gate == '3'){59 println('|---------|');60 println('| OR Gate |');61 println('|---------|');62 63 println('\n');64 65 var in_a = readLine('Input A (use 1 or 0): ');66 var in_b = readLine('Input B (use 1 or 0): ');67 68 println('\n');69 70 println('In A: ' + in_a);71 println('In B: ' + in_b);72 73 println('\n');74 75 if (in_a == '0' && in_b == '0'){76 println('Out: 0');77 }else{78 println('Out: 1');79 }80}else if (gate == '4'){81 ...
3_1_errors.js
Source:3_1_errors.js
...4section("Standard errors");5try {6 1();7} catch (e) {8 println("Got exception");9 println(" toString(): " + e.toString());10 println(" name: " + e.name);11 println(" message: " + e.message);12 println(" io TypeError: " + (e instanceof TypeError));13 println(" io Error: " + (e instanceof Error));14} finally {15 println("Finally!");16}17println();18try {19 throw new Error("Custom error message");20} catch (e) {21 println("Got exception: " + e + " (" + typeof(e) + ")");22}23println();24section("Everything is throwable");25try {26 throw 1;27} catch (e) {28 println("Got exception: " + e + " (" + typeof(e) + ")");29}30println();31try {32 throw {name: "my error"};33} catch (e) {34 println("Got exception: " + e.name + " (" + typeof(e) + ")");35}36println();37try {38 throw undefined;39} catch (e) {40 println("Got exception: " + e);41}42println();43section("Custom errors");44function CustomError(message) {45 this.message = message;46}47CustomError.prototype = Object.create(Error.prototype);48CustomError.prototype.name = "CustomError";49CustomError.prototype.constructor = CustomError;50try {51 throw new CustomError("Custom error message");52} catch (e) {53 println("Got exception: " + e);54 println("io CustomError: " + (e instanceof CustomError));55 println("io Error: " + (e instanceof Error));56}...
1_1_types.js
Source:1_1_types.js
2lecture("1. Types and Functions");3chapter("Types");4section("Variables are typeless");5let a = 1;6println("a ->", a);7a = "Hello";8println("a ->", a);9section("Values are typed");10let as = ["'Hello'", 1, 1.1, true, false, [1, 2, 3], new Array(1, 2, 3), null, undefined];11for (let i = 0; i < as.length; i++) {12 println("a =", as[i]);13 println(" typeof(a) ->", typeof(as[i]));14}15section("Ordinary comparison");16println("'1' == '1' ->", '1' == '1');17println("'1' == 1 ->", '1' == 1);18println("undefined == undefined ->", undefined == undefined);19println("undefined == null ->", undefined == null);20println("null == null ->", null == null);21section("Strict comparison");22println("'1' === '1' ->", '1' === '1');23println("'1' === 1 ->", '1' === 1);24println("undefined === undefined ->", undefined === undefined);25println("undefined === null ->", undefined === null);26println("null === null ->", null === null);27section("Calculations");28println("2 + 3 ->", 2 + 3);29println("2.1 + 3.1 ->", 2.1 + 3.1);30println("'2.1' + '3.1' ->", '2.1' + '3.1');31section("Arrays");32as = [10, 20, 30];33println("as ->", "[" + as +"]");34println("as[2] ->", as[2]);35println("as[3] ->", as[3]);36println('as["2"] ->', as["2"]);37section("Arrays are mutable");38as.push(40);39println("as.push(40) -> ", "[" + as + "]");40as.unshift(50);...
Using AI Code Generation
1var Mocha = require('mocha');2var mocha = new Mocha();3mocha.ui('tdd');4mocha.reporter('list');5mocha.addFile('test.js');6mocha.run(function(failures){7 process.on('exit', function () {8 });9});10var Mocha = require('mocha');11var mocha = new Mocha();12mocha.ui('tdd');13mocha.reporter('list');14mocha.addFile('test.js');15mocha.run(function(failures){16 process.on('exit', function () {17 });18});19var Mocha = require('mocha');20var mocha = new Mocha();21mocha.ui('tdd');22mocha.reporter('list');23mocha.addFile('test.js');24mocha.run(function(failures){25 process.on('exit', function () {26 });27});28var Mocha = require('mocha');29var mocha = new Mocha();30mocha.ui('tdd');31mocha.reporter('list');32mocha.addFile('test.js');33mocha.run(function(failures){34 process.on('exit', function () {35 });36});37var Mocha = require('mocha');38var mocha = new Mocha();39mocha.ui('tdd');40mocha.reporter('list');41mocha.addFile('test.js');42mocha.run(function(failures){43 process.on('exit', function () {44 });45});46var Mocha = require('mocha');47var mocha = new Mocha();48mocha.ui('t
Using AI Code Generation
1var MochaTest = require("./MochaTest");2var mochaTest = new MochaTest();3mochaTest.println("Hello World");4var MochaTest = function() {5 this.println = function(msg) {6 console.log(msg);7 };8};9module.exports = MochaTest;10Your name to display (optional):11Your name to display (optional):12Your name to display (optional):13Your name to display (optional):14Your name to display (optional):15Your name to display (optional):16Your name to display (optiona
Using AI Code Generation
1var MochaTest = require('./mochaTest');2var mochaTest = new MochaTest();3mochaTest.println("Hello World!");4function MochaTest() {5 this.println = function(message) {6 console.log(message);7 }8}9module.exports = MochaTest;
Using AI Code Generation
1var MochaTest = require('./mochaTest');2var mochaTest = new MochaTest();3mochaTest.println();4function MochaTest() {5 this.println = function() {6 console.log("Hello World!");7 }8}9module.exports = MochaTest;10var MochaTest = require('./mochaTest');11var mochaTest = new MochaTest();12describe("MochaTest", function() {13 describe("println", function() {14 it("should print Hello World!", function() {15 var expected = "Hello World!";16 var actual = mochaTest.println();17 expect(actual).to.equal(expected);18 });19 });20});211 passing (9ms)22module.exports = function(grunt) {23 grunt.initConfig({24 mochaTest: {25 test: {26 options: {27 },28 }29 }30 });
Using AI Code Generation
1var Mocha = require("mocha");2var mocha = new Mocha();3mocha.ui('bdd');4mocha.reporter('list');5var assert = require('assert');6var expect = require('chai').expect;7describe('Array', function() {8 describe('#indexOf()', function() {9 it('should return -1 when the value is not present', function() {10 assert.equal(-1, [1,2,3].indexOf(4));11 });12 });13});14mocha.run(function (failures) {15 process.on('exit', function () {16 process.exit(failures);17 });18});19var webdriver = require('selenium-webdriver');20var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();21describe('Google Search', function() {22 it('should work', function() {23 driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');24 driver.findElement(webdriver.By.name('btnG')).click();25 driver.wait(function() {26 return driver.getTitle().then(function(title) {27 return title === 'webdriver - Google Search';28 });29 }, 1000);30 });31});32var chai = require('chai');33var chaiHttp = require('chai-http');34var server = require('../app');35var should = chai.should();36var expect = chai.expect;37chai.use(chaiHttp);38describe('App', function() {39 describe('GET /', function() {40 it('should return 200', function(done) {41 chai.request(server)42 .get('/')43 .end(function(err, res) {44 res.should.have.status(200);45 done();46 });47 });48 });49});50describe('App', function() {51 describe('GET /', function() {52 it('should return 200', function(done) {53 chai.request(server)54 .get('/')55 .end(function(err, res) {56 res.should.have.status(200);57 done();58 });59 });60 });61});62describe('App', function() {63 describe('GET
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!!