How to use readArguments method in root

Best JavaScript code snippet using root

preloaded.ts

Source:preloaded.ts Github

copy

Full Screen

1import { Interpreter, RuntimeError } from './eval';2import { Parser, ParsingError } from './parser';3import {4 ReadPort,5 WritePort,6 getStdin,7 getStdout,8 systemExec,9 readFileToString,10 openFileWrite,11 openFileRead,12 abortExecution13} from './platform';14import {15 Boolean,16 cast,17 Character,18 Datum,19 DatumKind,20 Environment,21 Hash,22 Integer,23 mkBoolean,24 mkCharacter,25 mkHash,26 mkInteger,27 mkPair,28 mkPort,29 mkReal,30 mkString,31 mkSymbol,32 mkVector,33 mkVoid,34 Pair,35 pair,36 Port,37 Real,38 String,39 Symbol,40 toString,41 Vector,42} from './datum';43export const Preloaded: [string, (i: Interpreter, a: Datum[]) => Datum][] = [44 /**************/45 // Primitives //46 /**************/47 ['set!', setFn],48 ['exit', exitFn],49 ['load', loadFn],50 ['eval', evalFn],51 ['apply', applyFn],52 ['system', systemFn],53 ['void', voidFn],54 /*********************/55 // Boolean functions //56 /*********************/57 ['and', opBoolBoolToBool((a, b) => a && b)],58 ['or', opBoolBoolToBool((a, b) => a || b)],59 /***********************/60 // Character functions //61 /***********************/62 ['chr=?', opChrChrToBool((a, b) => a == b)],63 ['chr>?', opChrChrToBool((a, b) => a > b)],64 ['chr<?', opChrChrToBool((a, b) => a < b)],65 ['chr>=?', opChrChrToBool((a, b) => a >= b)],66 ['chr<=?', opChrChrToBool((a, b) => a <= b)],67 ['chr-digit?', opChrToBool(isDigit)],68 ['chr-alpha?', opChrToBool(isAlpha)],69 ['chr-alnum?', opChrToBool(isAlphaNum)],70 ['chr-space?', opChrToBool(isSpace)],71 ['chr-lower?', opChrToBool(isLower)],72 ['chr-upper?', opChrToBool(isUpper)],73 /*********************/74 // Numeric functions //75 /*********************/76 ['-', opNumNumToNum((a, b) => a - b)],77 ['+', opNumNumToNum((a, b) => a + b)],78 ['*', opNumNumToNum((a, b) => a * b)],79 ['/', opNumNumToNum((a, b) => a / b)],80 ['//', opNumNumToNum((a, b) => Math.floor(a / b))],81 ['mod', opNumNumToNum((a, b) => a % b)],82 ['=?', opNumNumToBool((a, b) => a == b)],83 ['<?', opNumNumToBool((a, b) => a < b)],84 ['>?', opNumNumToBool((a, b) => a > b)],85 ['/=?', opNumNumToBool((a, b) => a != b)],86 ['>=?', opNumNumToBool((a, b) => a >= b)],87 ['<=?', opNumNumToBool((a, b) => a <= b)],88 ['ceil', opRealToReal(Math.ceil)],89 ['floor', opRealToReal(Math.floor)],90 ['trunc', opRealToReal(Math.trunc)],91 ['round', opRealToReal(Math.round)],92 ['exp', opRealToReal(Math.exp)],93 ['log', opRealToReal(Math.log)],94 ['sin', opRealToReal(Math.sin)],95 ['cos', opRealToReal(Math.cos)],96 ['tan', opRealToReal(Math.tan)],97 ['asin', opRealToReal(Math.asin)],98 ['acos', opRealToReal(Math.acos)],99 ['atan', opRealToReal(Math.atan)],100 /********************/101 // String functions //102 /********************/103 ['str', strEmptyProc],104 ['str@', strAtProc],105 ['str+', strAppendProc],106 ['str-nl', strNewlineProc],107 ['str-len', strLenProc],108 ['str-sub', strSubstringProc],109 ['str-set!', strSetProc],110 ['str-fill!', strFillProc],111 ['str=?', opStrStrToBool((a, b) => a == b)],112 ['str<?', opStrStrToBool((a, b) => a < b)],113 ['str>?', opStrStrToBool((a, b) => a > b)],114 ['str<=?', opStrStrToBool((a, b) => a <= b)],115 ['str>=?', opStrStrToBool((a, b) => a >= b)],116 /********************/117 // Vector functions //118 /********************/119 ['vec', vecEmptyProc],120 ['vec@', vecAtProc],121 ['vec-len', vecLenProc],122 ['vec-set!', vecSetProc],123 ['vec-fill!', vecFillProc],124 /******************/125 // Hash functions //126 /******************/127 ['hash', hashEmptyProc],128 ['hash@', hashAtProc],129 ['hash-set!', hashSetProc],130 ['hash-keys', hashKeysProc],131 ['hash-vals', hashValsProc],132 /******************/133 // Pair functions //134 /******************/135 ['car', carProc],136 ['cdr', cdrProc],137 ['cons', consProc],138 ['nil?', isNilProc],139 ['list', listProc],140 /****************/141 // IO functions //142 /****************/143 ['read', readProc],144 ['write', writeProc],145 ['open-input-file', openInputFile],146 ['open-output-file', openOutputFile],147 ['close-input-port', closePort],148 ['close-output-port', closePort],149 ['read-contents', readContents],150 /*************************/151 // Polymorphic functions //152 /*************************/153 ['eq?', areEqual],154 ['same?', areSame],155 ['sym?', isOfDatumKind(DatumKind.Symbol)],156 ['bool?', isOfDatumKind(DatumKind.Boolean)],157 ['chr?', isOfDatumKind(DatumKind.Character)],158 ['int?', isOfDatumKind(DatumKind.Integer)],159 ['real?', isOfDatumKind(DatumKind.Real)],160 ['str?', isOfDatumKind(DatumKind.String)],161 ['vec?', isOfDatumKind(DatumKind.Vector)],162 ['hash?', isOfDatumKind(DatumKind.Hash)],163 ['port?', isOfDatumKind(DatumKind.Port)],164 ['list?', isOfDatumKind(DatumKind.Pair)],165 ['env?', isOfDatumKind(DatumKind.Environment)],166 ['proc?', isOfDatumKind(DatumKind.Procedure)],167 /**************************/168 // Type casting functions //169 /**************************/170 ['sym->str', symToStrProc],171 ['bool->str', boolToStrProc],172 ['chr->str', chrToStrProc],173 ['chr->int', chrToIntProc],174 ['int->chr', intToChrProc],175 ['num->str', numToStrProc],176 ['str->sym', strToSymProc],177 ['str->int', strToIntProc],178 ['str->real', strToRealProc],179 ['str->vec', strToVecProc],180 ['vec->str', vecToStrProc],181 ['vec->list', vecToListProc],182 ['hash->vec', hashToVecProc],183 ['hash->env', hashToEnvProc]184];185type DatumKinds<T extends [...Datum[]]> = { length: T['length'] } & {186 [I in keyof T]: T[I] extends Datum ? T[I]['kind'] | null : never187};188function noArguments(args: Datum[]) {189 if (args.length > 0) {190 throw new RuntimeError(191 `function called with ${args.length} argument(s):`192 + `${args.map(toString).join(', ')} but expected none`193 );194 }195}196function minArguments(args: Datum[], count: number) {197 if (args.length <= count) {198 throw new RuntimeError(199 `function called with ${args.length} argument(s) but`200 + ` needs at least ${count}`201 );202 }203}204function readArguments<T extends [...Datum[]]>(args: Datum[], kinds: DatumKinds<T>): T {205 if (args.length !== kinds.length) {206 throw new RuntimeError(207 `function called with ${args.length} argument(s)`208 + ` instead of ${kinds.length}`209 );210 }211 args.forEach((arg, i) => {212 if (kinds[i] && kinds[i] != arg.kind) {213 throw new RuntimeError(214 `argument '${toString(arg)}' (${i}) is of type ${arg.kind}, `215 + ` expected type ${kinds[i]}`216 );217 }218 });219 return args as T;220}221/**************/222// Primitives //223/**************/224function setFn(interp: Interpreter, args: Datum[]): Datum {225 const [name, value] = readArguments<[Symbol, Datum]>(args, [226 DatumKind.Symbol, null227 ]);228 return interp.environment().modify(name.value, value);229}230function exitFn(_: Interpreter, args: Datum[]): Datum {231 getStdout().write(`Exit was called ${args.map(toString).join(', ')}\n`);232 abortExecution();233}234function loadFn(interp: Interpreter, args: Datum[]): Datum {235 const [file] = readArguments<[String]>(args, [DatumKind.String]);236 const content = readFileToString(file.value);237 const data = new Parser()238 .parseLines(content)239 // @ts-ignore240 .map((result: Datum | ParsingError) => {241 if (result instanceof ParsingError) {242 throw result;243 } else {244 return interp.tryEvaluate(result);245 }246 });247 return pair(data);248}249function evalFn(interp: Interpreter, args: Datum[]): Datum {250 const [arg, env] = readArguments<[Datum, Environment]>(args, [251 null, DatumKind.Environment252 ]);253 const evaled = interp.evaluateWith(arg, env);254 if (evaled instanceof RuntimeError) {255 throw evaled;256 } else {257 return evaled;258 }259}260function applyFn(interp: Interpreter, args: Datum[]): Datum {261 minArguments(args, 1);262 const [fn, fnargs] = [args[0], args.slice(1)];263 return interp.tryEvaluate(mkPair(fn, pair(fnargs)));264}265function systemFn(_: Interpreter, args: Datum[]): Datum {266 minArguments(args, 1);267 const cmd = cast<String>(args[0], DatumKind.String).value;268 const options = args269 .slice(1)270 .map(d => cast<String>(d, DatumKind.String).value);271 const [stdin, stdout] = systemExec(cmd, options);272 return mkPair(mkPort(stdin), mkPort(stdout));273}274function voidFn(_: Interpreter, args: Datum[]): Datum {275 noArguments(args);276 return mkVoid();277}278/*********************/279// Boolean functions //280/*********************/281function opBoolBoolToBool(op: (a: boolean, b: boolean) => boolean) {282 return (_: Interpreter, args: Datum[]): Datum => {283 const [a, b] = readArguments<[Boolean, Boolean]>(284 args, [DatumKind.Boolean, DatumKind.Boolean]285 );286 return mkBoolean(op(a.value, b.value));287 };288}289/***********************/290// Character functions //291/***********************/292function isDigit(a: number): boolean {293 return '0'.charCodeAt(0) <= a && a <= '9'.charCodeAt(0);294}295function isAlpha(a: number): boolean {296 return !!String.fromCharCode(a).match(/(\p{Ll}|\p{Lu})/u);297}298function isAlphaNum(a: number): boolean {299 return isDigit(a) || isAlpha(a);300}301function isSpace(a: number): boolean {302 const str = String.fromCharCode(a);303 return str.trim() === str;304}305function isLower(a: number): boolean {306 const str = String.fromCharCode(a);307 return str.toLowerCase() === str;308}309function isUpper(a: number): boolean {310 const str = String.fromCharCode(a);311 return str.toUpperCase() === str;312}313function opChrChrToBool(op: (a: number, b: number) => boolean) {314 return (_: Interpreter, args: Datum[]): Datum => {315 const [a, b] = readArguments<[Character, Character]>(316 args, [DatumKind.Character, DatumKind.Character]317 );318 return mkBoolean(op(a.value, b.value));319 };320}321function opChrToBool(op: (a: number) => boolean) {322 return (_: Interpreter, args: Datum[]): Datum => {323 const [a] = readArguments<[Character]>(args, [DatumKind.Character]);324 return mkBoolean(op(a.value));325 };326}327/*********************/328// Numeric functions //329/*********************/330function opNumNumToNum(op: (a: number, b: number) => number) {331 return (_: Interpreter, args: Datum[]): Datum => {332 const [a, b] = readArguments<[Real | Integer, Real | Integer]>(333 args, [null, null]334 );335 return mkReal(op(a.value, b.value));336 };337}338function opNumNumToBool(op: (a: number, b: number) => boolean) {339 return (_: Interpreter, args: Datum[]): Datum => {340 const [a, b] = readArguments<[Real | Integer, Real | Integer]>(341 args, [null, null]342 );343 return mkBoolean(op(a.value, b.value));344 };345}346function opRealToReal(op: (x: number) => number) {347 return (_: Interpreter, args: Datum[]): Datum => {348 const [x] = readArguments<[Real]>(args, [DatumKind.Real]);349 return mkReal(op(x.value));350 };351}352/********************/353// String functions //354/********************/355function strEmptyProc(_: Interpreter, args: Datum[]): Datum {356 noArguments(args);357 return mkString('');358}359function strAtProc(_: Interpreter, args: Datum[]): Datum {360 const [str, idx] = readArguments<[String, Integer]>(args, [361 DatumKind.String, DatumKind.Integer,362 ]);363 if (idx.value >= str.value.length) {364 throw new RuntimeError(365 `index '${idx.value}' out of bounds of string`366 + ` with ${str.value.length} characters`367 );368 }369 return mkCharacter(str.value.charAt(idx.value));370}371function strAppendProc(_: Interpreter, args: Datum[]): Datum {372 const [a, b] = readArguments<[String, String]>(args, [373 DatumKind.String, DatumKind.String,374 ]);375 return mkString(a.value + b.value);376}377function strNewlineProc(_: Interpreter, args: Datum[]): Datum {378 const [str] = readArguments<[String]>(args, [DatumKind.String]);379 return mkString(str + '\n');380}381function strLenProc(_: Interpreter, args: Datum[]): Datum {382 const [str] = readArguments<[String]>(args, [DatumKind.String]);383 return mkInteger(str.value.length);384}385function strSubstringProc(_: Interpreter, args: Datum[]): Datum {386 const [str, start, end] = readArguments<[String, Integer, Integer]>(args, [387 DatumKind.String, DatumKind.Integer, DatumKind.Integer388 ]);389 if (start.value < 0 || str.value.length >= start.value) {390 throw new RuntimeError(391 `start value '${start.value}' out of bounds of string`392 + ` with ${str.value.length} characters`393 );394 }395 if (end.value < 0 || str.value.length >= end.value) {396 throw new RuntimeError(397 `end value '${end.value}' out of bounds of string`398 + ` with ${str.value.length} characters`399 );400 }401 if (start > end) {402 throw new RuntimeError(403 `substring range '${start.value}' to '${end.value}' is invalid`404 );405 }406 return mkString(str.value.substring(start.value, end.value));407}408function strSetProc(interp: Interpreter, args: Datum[]): Datum {409 const [name, idx, char] = readArguments<[Symbol, Integer, Character]>(args, [410 DatumKind.Symbol, DatumKind.Integer, DatumKind.Character411 ]);412 const str = cast<String>(413 interp.environment().read(name.value),414 DatumKind.String415 );416 if (idx.value >= str.value.length) {417 throw new RuntimeError(418 `index '${idx.value}' out of bounds of string`419 + ` with ${str.value.length} characters`420 );421 }422 const newStr = mkString(423 str.value.substring(0, idx.value)424 + String.fromCharCode(char.value)425 + str.value.substring(idx.value + 1)426 );427 interp.environment().write(name.value, newStr);428 return mkVoid();429}430function strFillProc(interp: Interpreter, args: Datum[]): Datum {431 const [name, char] = readArguments<[Symbol, Character]>(args, [432 DatumKind.Symbol, DatumKind.Character433 ]);434 const str = cast<String>(435 interp.environment().read(name.value),436 DatumKind.String437 );438 // JS's strings are immutable so we have to fake it.439 interp.environment().write(name.value, mkString(440 String.fromCharCode(char.value).repeat(str.value.length)441 ));442 return mkVoid();443}444function opStrStrToBool(op: (a: string, b: string) => boolean) {445 return (_: Interpreter, args: Datum[]): Datum => {446 const [a, b] = readArguments<[String, String]>(args, [447 DatumKind.String, DatumKind.String448 ]);449 return mkBoolean(op(a.value, b.value));450 };451}452/********************/453// Vector functions //454/********************/455function vecEmptyProc(_: Interpreter, args: Datum[]): Datum {456 noArguments(args);457 return mkVector();458}459function vecAtProc(_: Interpreter, args: Datum[]): Datum {460 const [vec, idx] = readArguments<[Vector, Integer]>(args, [461 DatumKind.Vector, DatumKind.Integer,462 ]);463 if (idx.value >= vec.value.length) {464 throw new RuntimeError(465 `index '${idx.value}' out of bounds of vector`466 + ` with ${vec.value.length} elements`467 );468 }469 return vec.value[idx.value];470}471function vecLenProc(_: Interpreter, args: Datum[]): Datum {472 const [vec] = readArguments<[Vector]>(args, [DatumKind.Vector]);473 return mkInteger(vec.value.length);474}475function vecSetProc(interp: Interpreter, args: Datum[]): Datum {476 const [name, idx, value] = readArguments<[Symbol, Integer, Datum]>(args, [477 DatumKind.Symbol, DatumKind.Integer, null478 ]);479 const vec = cast<Vector>(480 interp.environment().read(name.value),481 DatumKind.Vector482 );483 if (idx.value >= vec.value.length) {484 throw new RuntimeError(485 `index '${idx.value}' out of bounds of vector`486 + ` with ${vec.value.length} elements`487 );488 }489 vec.value[idx.value] = value;490 return mkVoid();491}492function vecFillProc(interp: Interpreter, args: Datum[]): Datum {493 const [name, value] = readArguments<[Symbol, Datum]>(args, [494 DatumKind.Symbol, null495 ]);496 const vec = cast<Vector>(497 interp.environment().read(name.value),498 DatumKind.Vector499 );500 vec.value.fill(value);501 return mkVoid();502}503/******************/504// Hash functions //505/******************/506function hashEmptyProc(_: Interpreter, args: Datum[]): Datum {507 return mkHash();508}509function hashAtProc(_: Interpreter, args: Datum[]): Datum {510 const [hash, key] = readArguments<[Hash, Datum]>(args, [511 DatumKind.Hash, null512 ]);513 const value = hash.value.get(hash);514 if (!value) {515 throw new RuntimeError(`hash does not contain key '${toString(key)}'`);516 }517 return value;518}519function hashSetProc(interp: Interpreter, args: Datum[]): Datum {520 const [name, key, value] = readArguments<[Symbol, Datum, Datum]>(args, [521 DatumKind.Symbol, null, null522 ]);523 // Read hash from environment524 const hash = cast<Hash>(525 interp.environment().read(name.value),526 DatumKind.Hash527 );528 hash.value.set(key, value);529 return mkVoid();530}531function hashKeysProc(_: Interpreter, args: Datum[]): Datum {532 const [hash] = readArguments<[Hash]>(args, [DatumKind.Hash]);533 return mkVector(...hash.value.keys());534}535function hashValsProc(_: Interpreter, args: Datum[]): Datum {536 const [hash] = readArguments<[Hash]>(args, [DatumKind.Hash]);537 return mkVector(...hash.value.values());538}539/******************/540// Pair functions //541/******************/542function carProc(_: Interpreter, args: Datum[]): Datum {543 const [x] = readArguments<[Pair]>(args, [DatumKind.Pair]);544 return x.left;545};546function cdrProc(_: Interpreter, args: Datum[]): Datum {547 const [x] = readArguments<[Pair]>(args, [DatumKind.Pair]);548 return x.right;549}550function consProc(_: Interpreter, args: Datum[]): Datum {551 const [car, cdr] = readArguments<[Datum, Datum]>(args, [null, null]);552 return mkPair(car, cdr);553}554function isNilProc(_: Interpreter, args: Datum[]): Datum {555 const [x] = readArguments<[Datum]>(args, [null]);556 return mkBoolean(x.kind === DatumKind.Symbol && x.value === '()');557}558function listProc(_: Interpreter, args: Datum[]): Datum {559 return pair(args);560}561/*************************/562// Polymorphic functions //563/*************************/564function areEqual(_: Interpreter, args: Datum[]): Datum {565 const [a, b] = readArguments<[Datum, Datum]>(args, [null, null]);566 return mkBoolean(JSON.stringify(a) === JSON.stringify(b));567}568function areSame(_: Interpreter, args: Datum[]): Datum {569 const [a, b] = readArguments<[Datum, Datum]>(args, [null, null]);570 return mkBoolean(a === b);571}572function isOfDatumKind(kind: DatumKind) {573 return (_: Interpreter, args: Datum[]): Datum => {574 const [arg] = readArguments<[Datum]>(args, [null]);575 return mkBoolean(arg.kind === kind);576 };577}578/****************/579// IO functions //580/****************/581function readProc(_: Interpreter, args: Datum[]): Datum {582 switch (args.length) {583 case 0: {584 return mkString(getStdin().read());585 }586 default: {587 const [port] = readArguments<[Port]>(args, [DatumKind.Port]);588 if (port.value instanceof WritePort) {589 throw new RuntimeError('port is write-only');590 }591 return mkString(port.value.read());592 }593 }594}595function writeProc(_: Interpreter, args: Datum[]): Datum {596 switch (args.length) {597 case 1: {598 const [str] = readArguments<[String]>(args, [DatumKind.String]);599 getStdout().write(str.value);600 return mkVoid();601 }602 default: {603 const [port, str] = readArguments<[Port, String]>(args, [604 DatumKind.Port, DatumKind.String605 ]);606 if (port.value instanceof ReadPort) {607 throw new RuntimeError('port is read-only');608 }609 port.value.write(str);610 return mkVoid();611 }612 }613}614function openInputFile(_: Interpreter, args: Datum[]): Datum {615 const [file] = readArguments<[String]>(args, [DatumKind.String]);616 return mkPort(openFileRead(file.value));617}618function openOutputFile(_: Interpreter, args: Datum[]): Datum {619 const [file] = readArguments<[String]>(args, [DatumKind.String]);620 return mkPort(openFileWrite(file.value));621}622function closePort(_: Interpreter, args: Datum[]): Datum {623 const [port] = readArguments<[Port]>(args, [DatumKind.Port]);624 port.value.destroy();625 return mkVoid();626}627function readContents(_: Interpreter, args: Datum[]): Datum {628 const [input] = readArguments<[String | Port]>(args, [null]);629 switch (input.kind) {630 case DatumKind.String: {631 return mkString(readFileToString(input.value));632 }633 case DatumKind.Port: {634 if (input.value instanceof WritePort) {635 throw new RuntimeError('port is write-only');636 }637 return mkString(input.value.read());638 }639 }640}641/**************************/642// Type casting functions //643/**************************/644function symToStrProc(_: Interpreter, args: Datum[]): Datum {645 const [sym] = readArguments<[Symbol]>(args, [DatumKind.Symbol]);646 return mkString(sym.value);647}648function boolToStrProc(_: Interpreter, args: Datum[]): Datum {649 const [bool] = readArguments<[Boolean]>(args, [DatumKind.Boolean]);650 return mkString(bool.value ? 'true' : 'false');651}652function chrToStrProc(_: Interpreter, args: Datum[]): Datum {653 const [char] = readArguments<[Character]>(args, [DatumKind.Character]);654 return mkString(String.fromCharCode(char.value));655}656function chrToIntProc(_: Interpreter, args: Datum[]): Datum {657 const [char] = readArguments<[Character]>(args, [DatumKind.Character]);658 return mkInteger(char.value);659}660function intToChrProc(_: Interpreter, args: Datum[]): Datum {661 const [int] = readArguments<[Integer]>(args, [DatumKind.Integer]);662 return mkCharacter(int.value);663}664function numToStrProc(_: Interpreter, args: Datum[]): Datum {665 const [num] = readArguments<[Integer | Real]>(args, [null]);666 return mkString(num.value.toString());667}668function strToSymProc(_: Interpreter, args: Datum[]): Datum {669 const [str] = readArguments<[String]>(args, [DatumKind.String]);670 return mkSymbol(str.value);671}672function strToIntProc(_: Interpreter, args: Datum[]): Datum {673 const [str] = readArguments<[String]>(args, [DatumKind.String]);674 return mkInteger(Number.parseInt(str.value));675}676function strToRealProc(_: Interpreter, args: Datum[]): Datum {677 const [str] = readArguments<[String]>(args, [DatumKind.String]);678 return mkReal(Number.parseFloat(str.value));679}680function strToVecProc(_: Interpreter, args: Datum[]): Datum {681 const [str] = readArguments<[String]>(args, [DatumKind.String]);682 return mkVector(683 ...Array.from(str.value)684 .map(c => c.charCodeAt(0))685 .map(mkCharacter)686 );687}688function vecToStrProc(_: Interpreter, args: Datum[]): Datum {689 const [vec] = readArguments<[Vector]>(args, [DatumKind.Vector]);690 return mkString(vec.value691 .map(d => cast<Character>(d, DatumKind.Character))692 .map(c => String.fromCharCode(c.value))693 .join('')694 );695}696function vecToListProc(_: Interpreter, args: Datum[]): Datum {697 const [vec] = readArguments<[Vector]>(args, [DatumKind.Vector]);698 return pair(vec.value);699}700function hashToVecProc(_: Interpreter, args: Datum[]): Datum {701 const [hash] = readArguments<[Hash]>(args, [DatumKind.Hash]);702 const vec = [] as Datum[];703 for (const [key, value] of hash.value.entries()) {704 vec.push(mkPair(key, value));705 }706 return mkVector(...vec);707}708function hashToEnvProc(_: Interpreter, args: Datum[]): Datum {709 const [hash] = readArguments<[Hash]>(args, [DatumKind.Hash]);710 const envMap = new Map<string, Datum>();711 for (const [key, value] of hash.value.entries()) {712 envMap.set(cast<String>(key, DatumKind.String).value, value);713 }714 return new Environment(envMap);...

Full Screen

Full Screen

tracing-test.js

Source:tracing-test.js Github

copy

Full Screen

1// Copyright 2014 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4(class TracingHelper {5 constructor(testRunner, session) {6 this._testRunner = testRunner;7 this._session = session;8 }9 startTracing() {10 return this.startTracingWithArguments({ "categories": "-*,disabled-by-default-devtools.timeline,devtools.timeline", "type": "", "options": "" });11 }12 startTracingAndSaveAsStream() {13 var args = {14 "categories": "-*,disabled-by-default-devtools.timeline,devtools.timeline",15 "type": "",16 "options": "",17 "transferMode": "ReturnAsStream"18 };19 return this.startTracingWithArguments(args);20 }21 async startTracingWithArguments(args) {22 await this._session.protocol.Tracing.start(args);23 this._testRunner.log("Recording started");24 }25 async stopTracing() {26 var devtoolsEvents = [];27 function dataCollected(reply) {28 var allEvents = reply.params.value;29 var filteredEvents = allEvents.filter(e => /devtools.timeline/.test(e.cat));30 devtoolsEvents = devtoolsEvents.concat(filteredEvents);31 };32 this._session.protocol.Tracing.onDataCollected(dataCollected);33 this._session.protocol.Tracing.end();34 await this._session.protocol.Tracing.onceTracingComplete();35 this._testRunner.log("Tracing complete");36 this._session.protocol.Tracing.offDataCollected(dataCollected);37 this._devtoolsEvents = devtoolsEvents;38 return devtoolsEvents;39 }40 async stopTracingAndReturnStream() {41 function dataCollected() {42 this._testRunner.log("FAIL: dataCollected event should not be fired when returning trace as stream.");43 }44 this._session.protocol.Tracing.onDataCollected(dataCollected);45 this._session.protocol.Tracing.end();46 var event = await this._session.protocol.Tracing.onceTracingComplete();47 this._testRunner.log("Tracing complete");48 this._session.protocol.Tracing.offDataCollected(dataCollected);49 return event.params.stream;50 }51 retrieveStream(streamHandle, offset, chunkSize) {52 var callback;53 var promise = new Promise(f => callback = f);54 var result = "";55 var had_eof = false;56 var readArguments = { handle: streamHandle };57 if (typeof chunkSize === "number")58 readArguments.size = chunkSize;59 var firstReadArguments = JSON.parse(JSON.stringify(readArguments));60 if (typeof offset === "number")61 firstReadArguments.offset = 0;62 this._session.protocol.IO.read(firstReadArguments).then(message => onChunkRead.call(this, message.result));63 // Assure multiple in-flight reads are fine (also, save on latencies).64 this._session.protocol.IO.read(readArguments).then(message => onChunkRead.call(this, message.result));65 return promise;66 function onChunkRead(response) {67 if (had_eof)68 return;69 result += response.data;70 if (response.eof) {71 // Ignore stray callbacks from proactive read requests.72 had_eof = true;73 callback(result);74 return;75 }76 this._session.protocol.IO.read(readArguments).then(message => onChunkRead.call(this, message.result));77 }78 }79 findEvents(name, ph, condition) {80 return this._devtoolsEvents.filter(e => e.name === name && e.ph === ph && (!condition || condition(e)));81 }82 findEvent(name, ph, condition) {83 var events = this.findEvents(name, ph, condition);84 if (events.length)85 return events[0];86 throw new Error("Couldn't find event " + name + " / " + ph + "\n\n in " + JSON.stringify(this.devtoolsEvents, null, 2));87 }88 filterEvents(callback) {89 return this._devtoolsEvents.filter(callback);90 }91 async invokeAsyncWithTracing(performActions) {92 await this.startTracing();93 var data = await this._session.evaluateAsync(`(${performActions.toString()})()`);94 await this.stopTracing();95 return data;96 }97 formattedEvents() {98 var formattedEvents = this._devtoolsEvents.map(e => e.name + (e.args.data ? '(' + e.args.data.type + ')' : ''));99 return JSON.stringify(formattedEvents, null, 2);100 }...

Full Screen

Full Screen

arg.test.ts

Source:arg.test.ts Github

copy

Full Screen

1import { ConfirmOption, InputOption, Option } from '@src/options';2import { readArguments } from './arg';3describe('adapters:arg', () => {4 describe('readArguments()', () => {5 it('should be defined', () => {6 expect(readArguments).toBeDefined();7 });8 describe('given a list of arguments & cli options', () => {9 let options: Option[];10 beforeEach(() => {11 options = [12 new ConfirmOption({13 priority: 1,14 name: 'copy',15 defaultValue: true,16 async initialize() {17 return;18 },19 }),20 new InputOption({21 priority: 1,22 name: 'author',23 defaultValue: 'mhamilton',24 async initialize() {25 return;26 },27 }),28 ];29 });30 test('when arguments list is empty, then should return an empty object', () => {31 const args: string[] = [];32 const result = readArguments(args, options);33 expect(result).toStrictEqual({});34 });35 test('when no argument matches some option, then should return an empty object', () => {36 const args = ['delete', 'me'];37 const result = readArguments(args, options);38 expect(result).toStrictEqual({});39 });40 test('when no flag argument matches some option, then should return an empty object', () => {41 const args = ['--force'];42 const result = readArguments(args, options);43 expect(result).toStrictEqual({});44 });45 describe('when some argument matches a confirm option', () => {46 test("with the complete flag, then should return an object mapping the confirm name and the argument's value", () => {47 const args = ['--copy'];48 const result = readArguments(args, options);49 expect(result).toStrictEqual({ copy: true });50 });51 test("with the short alias flag, then should return an object mapping the confirm name and the argument's value", () => {52 const args = ['-c'];53 const result = readArguments(args, options);54 expect(result).toStrictEqual({ copy: true });55 });56 });57 describe('when some argument matches an input option', () => {58 test("with the complete flag, then should return an object mapping the input name and the argument's value", () => {59 const args = ['--author', 'alovelace'];60 const result = readArguments(args, options);61 expect(result).toStrictEqual({ author: 'alovelace' });62 });63 test("with the short alias flag, then should return an object mapping the input name and the argument's value", () => {64 const args = ['-a', 'alovelace'];65 const result = readArguments(args, options);66 expect(result).toStrictEqual({ author: 'alovelace' });67 });68 });69 });70 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require('./root');2var args = root.readArguments();3console.log(args);4var readArguments = function(){5 return process.argv;6}7module.exports.readArguments = readArguments;8console.log(process.argv);9var argv = require('minimist')(process.argv.slice(2));10console.log(argv);11{ _: [], name: 'John', age: '25' }12var argv = require('yargs')13 .usage('Usage: $0 --name [string] --age [num]')14 .demand(['name'])15 .argv;16console.log(argv);17{ _: [], name: 'John', age: 25, '$0': 'test.js' }

Full Screen

Using AI Code Generation

copy

Full Screen

1const root = require('./root');2const args = root.readArguments();3console.log(args);4const root = require('./root');5const args = root.readArguments();6console.log(args);

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = require("./root");2var args = root.readArguments();3console.log("args = " + args);4var rootPath = root.getRootPath();5console.log("rootPath = " + rootPath);6var rootPath = root.getRootPath();7console.log("rootPath = " + rootPath);8var rootPath = root.getRootPath();9console.log("rootPath = " + rootPath);10var rootPath = root.getRootPath();11console.log("rootPath = " + rootPath);12var rootPath = root.getRootPath();13console.log("rootPath = " + rootPath);14var rootPath = root.getRootPath();15console.log("rootPath = " + rootPath);16var rootPath = root.getRootPath();17console.log("rootPath = " + rootPath);18var rootPath = root.getRootPath();19console.log("rootPath = " + rootPath);

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful