How to use shrinkBigInt method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

language.ts

Source:language.ts Github

copy

Full Screen

1import util from 'util';2import { merge } from 'merge-anything';3import { isPlainObject } from 'is-what';4import { iterator, AnyIterable, AnyIterator } from './iterable';5import {6 LanguageReprs,7 LanguageFormat,8 LanguageConsts,9 LanguageDefinition,10 ReprAllTypes,11 ReprContainerType,12 ReprType,13 ReprFunction,14 ReprReturn,15 ReprIterableFunction,16 StackInterface,17 Shrink,18 LanguageInterface19} from './language-types';20export { LanguageDefinition };21const isDate = util.types.isDate;22export const REPR: symbol = Symbol('repr');23const reprObject = async function*(24 object: { [key: string]: any },25 lang: LanguageInterface,26 stack: StackInterface27) {28 if (!lang.format.object) {29 return;30 }31 const format = lang.format.object;32 const formatKey = format.key;33 lang.unsupported(formatKey, `[key] of objects`);34 let { sep, start, end, assign } = format;35 const entries = Object.entries(object);36 yield start;37 stack.push('object');38 for await (const [key, value] of entries) {39 yield `${formatKey(key, lang)}${assign}`;40 yield* lang.pull(value, stack);41 yield sep;42 }43 stack.pop();44 yield end;45};46// convert to language array/list47const reprIterable = async function*(48 iterable: AnyIterable,49 lang: LanguageInterface,50 stack: StackInterface,51 length?: number52): AnyIterable<string> {53 if (!lang.format.iterable) {54 return;55 }56 const { sep, start, end } = lang.format.iterable;57 const iter = iterator(iterable) as AnyIterable & AnyIterator;58 if (start) yield start;59 stack.push('iterable');60 const first = await iter.next();61 if (!first.done) {62 yield* lang.pull(first.value, stack);63 }64 // handle remaining65 for await (const value of iter) {66 yield sep;67 yield* lang.pull(value, stack);68 }69 stack.pop();70 if (end) yield end;71};72// default is double quoted strings73const reprString = (value: string) => `"${value.replace(/[\\"]/g, '\\$&')}"`;74const reprBoolean = (value: boolean, lang: LanguageInterface) =>75 value ? lang.consts.true || 'true' : lang.consts.false || 'false';76const reprDate = (date: Date, lang: LanguageInterface, stack: StackInterface) =>77 lang.reprs.string!(date.toISOString(), lang, stack);78const reprBigInt = String;79const reprNumber = String;80const validName = /^[a-zA-Z_]\w+$/;81const formatName = (value: string, lang: LanguageInterface) => {82 lang.invalid(validName.test(value), `${value}`, 'name');83 return value;84};85const validShrink = new Set(Object.values(Shrink));86const normalizeShrink = (value: boolean | Shrink): Shrink => {87 if (value === true) {88 return Shrink.ALL;89 } else if (value === false) {90 return Shrink.NONE;91 }92 return value;93};94export const defaults: Required<LanguageDefinition> = {95 shrinkBigInt: Shrink.SMALL,96 reprs: {97 string: reprString,98 boolean: reprBoolean,99 number: reprNumber,100 bigint: reprBigInt,101 date: reprDate,102 iterable: reprIterable,103 object: reprObject104 },105 consts: {106 true: 'true',107 false: 'false',108 null: null,109 invalid_date: null,110 nan: null,111 positive_infinity: null,112 negative_infinity: null,113 undefined: null114 },115 format: {116 indent: ' ',117 eol: '\n',118 declare: {119 name: formatName,120 assign: ' = ',121 start: '[',122 end: ']',123 sep: ', '124 },125 // 2 space indentation126 iterable: {127 sep: ', ',128 start: '[',129 end: ']',130 // array of types that are valid131 valid: false,132 // array of types that are invalid133 invalid: false134 },135 object: {136 key: reprString,137 sep: ', ',138 start: '{',139 end: '}',140 assign: ': ',141 // array of types that are valid142 valid: false,143 // array of types that are invalid144 invalid: false145 // break into new146 // into length147 }148 }149};150export class Stack implements StackInterface {151 top?: { type: ReprAllTypes; indent: string };152 stack: { type: ReprAllTypes; indent: string }[];153 constructor() {154 this.top = undefined;155 this.stack = [];156 }157 push(type: ReprAllTypes, indent?: string) {158 const defIndent = (this.top && this.top.indent) || '';159 const item = {160 type,161 indent: indent != null ? indent : defIndent162 };163 this.top = item;164 this.stack.push(item);165 return this.top;166 }167 pop() {168 return (this.top = this.stack.pop());169 }170}171const createStack = (root: ReprContainerType = 'root'): StackInterface => {172 const stack = new Stack();173 stack.push(root);174 return stack;175};176export class Language {177 name: string;178 shrinkBigInt: Shrink;179 reprs: LanguageReprs;180 consts: LanguageConsts;181 format: LanguageFormat;182 static isLanguage(value: any): value is Language {183 return value && value instanceof Language;184 }185 constructor(name: string, config: LanguageDefinition) {186 this.name = name;187 const shrink = config.shrinkBigInt;188 if (shrink === false) {189 this.shrinkBigInt = Shrink.NONE;190 } else if (shrink === true) {191 this.shrinkBigInt = Shrink.ALL;192 } else if (shrink) {193 if (!validShrink.has(shrink)) {194 throw new Error(`${shrink} must be one of ${validShrink}`);195 }196 this.shrinkBigInt = shrink;197 } else {198 this.shrinkBigInt = normalizeShrink(defaults.shrinkBigInt);199 }200 // @ts-ignore201 this.format = merge(defaults.format, config.format || {});202 this.reprs = merge(defaults.reprs, config.reprs || {});203 this.consts = merge(defaults.consts, config.consts || {});204 }205 type(val: any): ReprType {206 let type: ReprType = typeof val;207 if (type === 'number') {208 if (Number.isNaN(val)) {209 type = 'nan';210 } else if (val === Number.NEGATIVE_INFINITY) {211 type = 'negative_infinity';212 } else if (val === Number.POSITIVE_INFINITY) {213 type = 'positive_infinity';214 }215 } else if (type === 'object') {216 if (val === null) {217 type = 'null';218 } else if (REPR in val) {219 // supports the repr protocol220 return 'repr';221 } else if (Symbol.iterator in val || Symbol.asyncIterator in val) {222 type = 'iterable';223 } else if (isDate(val)) {224 type = isNaN((val as unknown) as number)225 ? 'invalid_date'226 : 'date';227 } else if (isPlainObject(val)) {228 type = 'object';229 } else {230 type = 'custom';231 }232 }233 return type;234 }235 invalid(condition: any, what: string, type: string): asserts condition {236 if (!condition) {237 throw new Error(`${what} is an invalid ${type} for ${this.name}`);238 }239 }240 unsupported(condition: any, what: string): asserts condition {241 if (!condition) {242 throw new Error(`${what} not supported by ${this.name}`);243 }244 }245 maybeShrink(246 val: bigint,247 bigintRepr: ReprFunction<bigint> | null | undefined,248 stack: StackInterface249 ) {250 // handle bigint251 const shrink = this.shrinkBigInt;252 if (253 shrink === Shrink.ALL ||254 (shrink === Shrink.SMALL &&255 !(256 val < Number.MIN_SAFE_INTEGER ||257 val > Number.MAX_SAFE_INTEGER258 ))259 ) {260 // change for error message261 const repr = this.reprs.number;262 this.unsupported(repr, `[number] (from [bigint])`);263 return repr(Number(val), this, stack);264 }265 this.unsupported(bigintRepr, `[bigint]`);266 return bigintRepr(val, this, stack);267 }268 allowedWithin(type: ReprType, parent: ReprType | ReprContainerType) {269 const details = (this.format as { [key: string]: any })[type];270 if (271 details &&272 // black list273 ((details.invalid && details.invalid.indexOf(parent) > 0) ||274 // white list275 (details.valid && details.valid.indexOf(parent) < 0))276 ) {277 return false;278 }279 return true;280 }281 // ensure this type is allowed in it's parent type282 assertAllowed(type: ReprType, stack: StackInterface) {283 const top = stack.top;284 if (top && !this.allowedWithin(type, top.type)) {285 throw new Error(286 `[${type}] not allowed in [${top.type}] for ${this.name}`287 );288 }289 }290 // get language representation of value291 repr(value: any, stack: StackInterface): ReprReturn {292 let type = this.type(value);293 if (type === 'repr') {294 // value supports repr protocol so return295 // return can be a function|promise<string|function>296 // functions will be called repeatedly until not a function is resolved297 // also iterable/asyncIterable<string> can be returnedÎÎ298 return value[REPR];299 }300 const constant = this.consts[type];301 if (constant != null) {302 return constant;303 }304 const repr: ReprFunction<any> = this.reprs[type];305 // handle big int306 if (type === 'bigint') {307 return this.maybeShrink(value, repr, stack);308 }309 this.assertAllowed(type, stack);310 this.unsupported(repr, `[${type}]`);311 if (type === 'iterable') {312 // pass in length313 const length = Array.isArray(value) ? value.length : undefined;314 return (repr as ReprIterableFunction)(value, this, stack, length);315 }316 return repr(value, this, stack);317 }318 async *declare(319 entries: Iterable<[string, any]>,320 stack?: StackInterface | ReprContainerType321 ): AsyncGenerator<string, void> {322 if (!this.format.declare) {323 return;324 }325 if (!stack || typeof stack === 'string') {326 stack = createStack(stack ?? 'declare');327 }328 const { start, end, name, assign } = this.format.declare;329 if (start) {330 yield start;331 }332 for (const [key, value] of entries) {333 yield `${name(key, this)}${assign}`;334 yield* this.pull(value, stack);335 }336 if (end) {337 yield end;338 }339 }340 // ensure a repr return value is correctly used341 async *pull(342 value: any,343 stack?: StackInterface | ReprContainerType344 ): AsyncGenerator<string, void> {345 if (!stack || typeof stack === 'string') {346 stack = createStack(stack);347 }348 let result = await this.repr(await value, stack);349 // pull nested results;350 while (result && typeof result === 'function') {351 result = await result();352 }353 if (!result) {354 return;355 }356 // result should either be a string or iterable357 if (typeof result === 'string') {358 yield result;359 } else if (360 Symbol.iterator in result ||361 Symbol.asyncIterator in result362 ) {363 yield* result;364 } else {365 // unrepresented return value366 yield '';367 }368 }...

Full Screen

Full Screen

ShrinkBigInt.spec.ts

Source:ShrinkBigInt.spec.ts Github

copy

Full Screen

...10 it('should always return empty stream when current equals target', () =>11 fc.assert(12 fc.property(fc.bigInt(), fc.boolean(), (value, tryAsap) => {13 // Arrange / Act14 const shrinks = [...shrinkBigInt(value, value, tryAsap)];15 // Assert16 expect(shrinks).toHaveLength(0);17 })18 ));19 it('should always starts stream with target when try asap is requested (when current not target)', () =>20 fc.assert(21 fc.property(fc.bigInt(), fc.bigInt(), (current, target) => {22 // Arrange23 fc.pre(current !== target);24 // Act25 const shrinks = [...shrinkBigInt(current, target, true)];26 // Assert27 expect(shrinks).not.toHaveLength(0);28 expect(shrinks[0].value).toBe(target);29 expect(shrinks[0].context).toBe(undefined);30 })31 ));32 it('should only include values between current and target in the stream', () =>33 fc.assert(34 fc.property(fc.bigInt(), fc.bigInt(), fc.boolean(), (current, target, tryAsap) => {35 // Arrange / Act36 const shrinks = [...shrinkBigInt(current, target, tryAsap)];37 const values = shrinks.map((v) => v.value);38 const min = (a: bigint, b: bigint) => (a < b ? a : b);39 const max = (a: bigint, b: bigint) => (a < b ? b : a);40 // Assert41 for (const v of values) {42 expect(v).toBeGreaterThanOrEqual(min(current, target));43 expect(v).toBeLessThanOrEqual(max(current, target));44 }45 })46 ));47 it('should never include current in the stream', () =>48 fc.assert(49 fc.property(fc.bigInt(), fc.bigInt(), fc.boolean(), (current, target, tryAsap) => {50 // Arrange / Act51 const shrinks = [...shrinkBigInt(current, target, tryAsap)];52 const values = shrinks.map((v) => v.value);53 // Assert54 expect(values).not.toContain(current);55 })56 ));57 it('should never include target in the stream when try asap is not requested', () =>58 fc.assert(59 fc.property(fc.bigInt(), fc.bigInt(), (current, target) => {60 // Arrange / Act61 const shrinks = [...shrinkBigInt(current, target, false)];62 const values = shrinks.map((v) => v.value);63 // Assert64 expect(values).not.toContain(target);65 })66 ));67 it('should always set context to be the value of previous entry in the stream', () =>68 fc.assert(69 fc.property(fc.bigInt(), fc.bigInt(), fc.boolean(), (current, target, tryAsap) => {70 // Arrange / Act71 const shrinks = [...shrinkBigInt(current, target, tryAsap)];72 // Assert73 for (let idx = 1; idx < shrinks.length; ++idx) {74 expect(shrinks[idx].context).toBe(shrinks[idx - 1].value);75 }76 })77 ));78 it('should specify first context of the stream to target if and only if no try asap, undefined otherwise', () =>79 fc.assert(80 fc.property(fc.bigInt(), fc.bigInt(), fc.boolean(), (current, target, tryAsap) => {81 // Arrange82 const expectedFirstContext = tryAsap ? undefined : target;83 // Act84 const first = shrinkBigInt(current, target, tryAsap).getNthOrLast(0);85 // Assert86 if (first !== null) {87 expect(first.context).toBe(expectedFirstContext);88 }89 })90 ));91 it('should always strictly increase distance from target as we move in the stream', () =>92 fc.assert(93 fc.property(fc.bigInt(), fc.bigInt(), fc.boolean(), (current, target, tryAsap) => {94 // Arrange / Act95 const shrinks = [...shrinkBigInt(current, target, tryAsap)];96 const absDiff = (a: bigint, b: bigint): bigint => {97 const result = a - b;98 return result >= 0 ? result : -result;99 };100 // Assert101 for (let idx = 1; idx < shrinks.length; ++idx) {102 const previousDistance = absDiff(shrinks[idx - 1].value, target);103 const currentDistance = absDiff(shrinks[idx].value, target);104 expect(currentDistance).toBeGreaterThan(previousDistance);105 }106 })107 ));...

Full Screen

Full Screen

shrinkBigInt.ts

Source:shrinkBigInt.ts Github

copy

Full Screen

1/**2 * @tsplus static effect/core/testing/Sample.Ops shrinkBigInt3 */4export function shrinkBigInt(smallest: bigint) {5 return (a: bigint): Sample<never, bigint> =>6 Sample.unfold(a, (max) =>7 Tuple(8 max,9 Stream.unfold(smallest, (min) => {10 const mid = min + (max - min) / BigInt(2)11 if (mid === max) {12 return Maybe.none13 } else if (bigIntAbs(max - mid) === BigInt(1)) {14 return Maybe.some(Tuple(mid, max))15 } else {16 return Maybe.some(Tuple(mid, mid))17 }18 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const {shrinkBigInt} = require('fast-check');2const {shrinkNumber} = require('fast-check');3const {shrinkString} = require('fast-check');4const {shrinkArray} = require('fast-check');5const {shrinkObject} = require('fast-check');6const bigint = 123n;7const number = 123;8const string = 'abc';9const array = ['a', 'b', 'c'];10const object = {a: 1, b: 2, c: 3};11const shrinkedBigInt = shrinkBigInt(bigint);12const shrinkedNumber = shrinkNumber(number);13const shrinkedString = shrinkString(string);14const shrinkedArray = shrinkArray(array);15const shrinkedObject = shrinkObject(object);16console.log(shrinkedBigInt);17console.log(shrinkedNumber);18console.log(shrinkedString);19console.log(shrinkedArray);20console.log(shrinkedObject);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { shrinkBigInt } = require('fast-check');2const bigInt = 12345678901234567890n;3const shrunkBigInt = shrinkBigInt(bigInt);4console.log(shrunkBigInt);5const { Arbitrary } = require('fast-check');6const bigInt = 12345678901234567890n;7const shrunkBigInt = Arbitrary.shrinkBigInt(bigInt);8console.log(shrunkBigInt);9if (bigInt === 0n) {10 return 0n;11}12if (bigInt === 1n) {13 return 0n;14}15if (bigInt === 2n) {16 return 1n;17}18if (bigInt === -1n) {19 return 0n;20}21if (bigInt === -2n) {22 return -1n;23}24if (bigInt % 2n === 0n) {25 return bigInt / 2n;26}27return (bigInt - 1n) / 2n;

Full Screen

Using AI Code Generation

copy

Full Screen

1var fc = require('fast-check');2var bigInt = require('big-integer');3var shrinkBigInt = require('fast-check/lib/arbitrary/helpers/ShrinkBigInt.js').shrinkBigInt;4var arb = fc.bigInt();5var value = bigInt('12345678901234567890');6var shrunk = shrinkBigInt(value, arb);7console.log(shrunk);8var fc = require('fast-check');9var bigInt = require('big-integer');10var shrinkBigInt = require('fast-check/lib/arbitrary/helpers/ShrinkBigInt.js').shrinkBigInt;11var arb = fc.bigInt();12var value = bigInt('12345678901234567890');13var shrunk = shrinkBigInt(value, arb);14var expected = [ 1234567890123456789n, 123456789012345679n, 12345678901234568n, 1234567890123457n, 123456789012346n, 12345678901235n, 1234567890124n, 123456789013n, 12345678902n, 1234567891n, 123456790n, 12345679n, 1234568n, 123457n, 12346n, 1235n, 124n, 13n, 2n, 1n ];15test('ShrinkBigInt method', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { shrinkBigInt } = require("fast-check");2const bigInt = 1234567890123456789n;3const shrunkBigInt = shrinkBigInt(bigInt);4console.log(shrunkBigInt);5const { shrinkBigInt } = require("fast-check");6const bigInt = 1234567890123456789n;7const shrunkBigInt = shrinkBigInt(bigInt);8console.log(shrunkBigInt);9const { shrinkBigInt } = require("fast-check");10const bigInt = 1234567890123456789n;11const shrunkBigInt = shrinkBigInt(bigInt);12console.log(shrunkBigInt);13const { shrinkBigInt } = require("fast-check");14const bigInt = 1234567890123456789n;15const shrunkBigInt = shrinkBigInt(bigInt);16console.log(shrunkBigInt);17const { shrinkBigInt } = require("fast-check");18const bigInt = 1234567890123456789n;19const shrunkBigInt = shrinkBigInt(bigInt);20console.log(shrunkBigInt);21const { shrinkBigInt } = require("fast-check");22const bigInt = 1234567890123456789n;23const shrunkBigInt = shrinkBigInt(bigInt);24console.log(shrunkBigInt);25const { shrinkBigInt } = require("fast-check");26const bigInt = 1234567890123456789n;27const shrunkBigInt = shrinkBigInt(bigInt);

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { shrinkBigInt } = require('fast-check/lib/src/check/arbitrary/definition/Shrinkable.js');3const bigIntArb = fc.bigInt();4const bigIntShrink = shrinkBigInt(bigIntArb);5const bigIntShrinkable = bigIntArb.generate(fc.random(42));6console.log(bigIntShrinkable.value);7console.log(bigIntShrink(bigIntShrinkable));

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const shrinkBigInt = require('fast-check/lib/arbitrary/shrinkBigInt').shrinkBigInt;3const bigIntArb = fc.bigInt();4fc.assert(5 fc.property(bigIntArb, (n) => {6 const shrinked = shrinkBigInt(n);7 return shrinked.every((s) => s < n);8 })9);

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 fast-check-monorepo 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