Best JavaScript code snippet using fast-check-monorepo
modifiers.ts
Source:modifiers.ts  
1/*2 * Copyright (c) 2017 MolQL contributors, licensed under MIT, See LICENSE file for more info.3 *4 * @author David Sehnal <david.sehnal@gmail.com>5 */6import Environment from '../environment'7import Expression from '../expression'8import Context from '../context'9import AtomSet from '../../data/atom-set'10import AtomSelection from '../../data/atom-selection'11import { UniqueArrayBuilder, sortAsc, FastSet, FastMap } from '../../../utils/collections'12import Mask from '../../../utils/mask'13import { Model, Bonds } from '../../../structure/data'14import ElementAddress from '../../data/element-address'15import BondAddress from '../../data/bond-address'16import { defaultBondTest, testBond, BondTest, maxAtomValueInSelection } from './common'17import AtomSetIt = AtomSet.Iterator18type Selection = Expression<AtomSelection>19export function queryEach(env: Environment, selection: Selection, query: Selection): AtomSelection {20    const builder = AtomSelection.uniqueBuilder();21    for (const atomSet of AtomSelection.atomSets(selection(env))){22        const ctx = Context.ofAtomSet(env.context, atomSet);23        for (const mappedAtomSet of AtomSelection.atomSets(query(Environment(ctx)))) {24            builder.add(mappedAtomSet);25        }26    }27    return builder.getSelection();28}29export function intersectBy(env: Environment, selection: Selection, by: Selection): AtomSelection {30    const mask = AtomSelection.getMask(by(env));31    const builder = AtomSelection.uniqueBuilder();32    const it = AtomSetIt();33    for (const atomSet of AtomSelection.atomSets(selection(env))) {34        let count = 0;35        for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {36            if (mask.has(a)) count++;37        }38        if (!count) continue;39        const intersection = new Int32Array(count);40        let offset = 0;41        for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {42            if (mask.has(a)) intersection[offset++] = a;43        }44        builder.add(AtomSet(intersection));45    }46    return builder.getSelection();47}48export function exceptBy(env: Environment, selection: Selection, by: Selection): AtomSelection {49    const mask = AtomSelection.getMask(by(env));50    const builder = AtomSelection.uniqueBuilder();51    const it = AtomSetIt();52    for (const atomSet of AtomSelection.atomSets(selection(env))) {53        let count = 0;54        for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {55            if (!mask.has(a)) count++;56        }57        if (!count) continue;58        const complement = new Int32Array(count);59        let offset = 0;60        for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {61            if (!mask.has(a)) complement[offset++] = a;62        }63        builder.add(AtomSet(complement));64    }65    return builder.getSelection();66}67export function unionBy(env: Environment, selection: Selection, by: Selection): AtomSelection {const atomCount = env.context.model.atoms.count;68    const atomSets = AtomSelection.atomSets(selection(env));69    const glue = by(env);70    const occurenceCount = new Int32Array(atomCount);71    const it = AtomSetIt();72    for (const atomSet of atomSets) {73        for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {74            occurenceCount[a]++;75        }76    }77    let totalOccurences = 0;78    const occurentOffsets = new Int32Array(atomCount);79    let offset = 0;80    for (const oc of occurenceCount as any as number[]) {81        occurentOffsets[offset++] = totalOccurences;82        totalOccurences += oc;83    }84    let setIndex = 0;85    const atomMap = new Int32Array(totalOccurences);86    const atomFill = new Int32Array(atomCount);87    for (const atomSet of atomSets) {88        for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {89            offset = occurentOffsets[a] + atomFill[a];90            atomFill[a]++;91            atomMap[offset] = setIndex;92        }93        setIndex++;94    }95    const builder = AtomSelection.uniqueBuilder();96    for (const glueSet of AtomSelection.atomSets(glue)) {97        const toGlue = UniqueArrayBuilder<number>();98        for (let a = AtomSetIt.start(it, glueSet); !it.done; a = it.next().value) {99            const o = occurentOffsets[a];100            for (let i = 0, _i = occurenceCount[a]; i < _i; i++) {101                const key = atomMap[o + i];102                UniqueArrayBuilder.add(toGlue, key, key);103            }104        }105        const indices = UniqueArrayBuilder<number>();106        for (const atomSetIndex of toGlue.array) {107            for (let a = AtomSetIt.start(it, atomSets[atomSetIndex]); !it.done; a = it.next().value) {108                UniqueArrayBuilder.add(indices, a, a);109            }110        }111        builder.add(AtomSet(sortAsc(indices.array)));112    }113    return builder.getSelection();114}115export function union(env: Environment, selection: Selection): AtomSelection {116    const sel = selection(env);117    if (!AtomSelection.atomSets(sel).length) return AtomSelection.empty;118    return AtomSelection([AtomSet(AtomSelection.getAtomIndices(selection(env)))]);119}120export interface ClusterParams {121    selection: Selection,122    minDist?: Expression<number>,123    maxDist: Expression<number>,124    minSize?: Expression<number>,125    maxSize?: Expression<number>126}127interface ClusterCtx {128    minDist: number,129    maxDist: number,130    minSize: number,131    maxSize: number,132    selection: AtomSelection,133    builder: AtomSelection.Builder,134    model: Model135}136function clusterAround(ctx: ClusterCtx, a: AtomSet, included: number[], candidates: number[]) {137    const depth = included.length;138    if (depth >= ctx.minSize) {139        ctx.builder.add(a);140    }141    if (depth >= ctx.maxSize || depth >= candidates.length) {142        return;143    }144    const { minDist, maxDist } = ctx;145    const atomSets = AtomSelection.atomSets(ctx.selection);146    const lastIncluded = included[included.length - 1];147    for (const bI of candidates) {148        if (bI <= lastIncluded) continue;149        const b = atomSets[bI];150        let canInclude = true;151        for (const iI of included) {152            const dist = AtomSet.distance(ctx.model, b, atomSets[iI]);153            if (dist < minDist || dist > maxDist) {154                canInclude = false;155                break;156            }157        }158        if (!canInclude) continue;159        included.push(bI);160        clusterAround(ctx, AtomSet.union(a, b), included, candidates);161        included.pop();162    }163}164function _cluster(ctx: ClusterCtx) {165    let i = 0;166    const lookup = AtomSelection.lookup3d(ctx.model, ctx.selection);167    for (const atomSet of AtomSelection.atomSets(ctx.selection)) {168        const candidates = lookup.queryAtomSet(atomSet, ctx.maxDist);169        sortAsc(candidates);170        clusterAround(ctx, atomSet, [i], candidates);171        i++;172    }173}174export function cluster(env: Environment, params: ClusterParams): AtomSelection {175    const cCtx: ClusterCtx = {176        selection: params.selection(env),177        minDist: (params.minDist && params.minDist(env)) || 0,178        maxDist: (params.maxDist && params.maxDist(env)),179        minSize: Math.max((params.minSize && params.minSize(env)) || 2, 2),180        maxSize: (params.maxSize && params.maxSize(env)) || Number.POSITIVE_INFINITY,181        builder: AtomSelection.linearBuilder(),182        model: env.context.model183    };184    _cluster(cCtx);185    return cCtx.builder.getSelection();186}187export interface IncludeSurroundingsParams {188    selection: Selection,189    radius: Expression<number>,190    atomRadius?: Expression<number>,191    wholeResidues?: Expression<boolean>192}193interface IncludeSurroundingsContext {194    env: Environment,195    selection: AtomSelection,196    radius: number,197    atomRadius: Expression<number>,198    wholeResidues: boolean199}200function _zeroRadius(env: Environment) { return 0; }201function includeSurroundingsNoRadius(ctx: IncludeSurroundingsContext) {202    const { env, selection, radius: r, wholeResidues } = ctx;203    const { model, mask } = env.context;204    const findWithin = Model.spatialLookup(model).find(mask);205    const { x, y, z } = model.positions;206    const { residueIndex } = model.atoms;207    const { atomOffset } = model.residues;208    const builder = AtomSelection.uniqueBuilder();209    const includedResides = FastSet.create<number>();210    const it = AtomSetIt();211    for (const atomSet of AtomSelection.atomSets(selection)) {212        const atoms = UniqueArrayBuilder<number>();213        for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {214            const { count, indices } = findWithin(x[a], y[a], z[a], r);215            for (let i = 0, _i = count; i < _i; i++) {216                const b = indices[i];217                if (wholeResidues) {218                    const rI = residueIndex[b];219                    if (includedResides.has(rI)) continue;220                    includedResides.add(rI);221                    for (let j = atomOffset[rI], _j = atomOffset[rI + 1]; j < _j; j++) {222                        if (!mask.has(j)) continue;223                        UniqueArrayBuilder.add(atoms, j, j);224                    }225                } else {226                    UniqueArrayBuilder.add(atoms, b, b);227                }228            }229        }230        builder.add(AtomSet(sortAsc(atoms.array)));231    }232    return builder.getSelection();233}234function includeSurroundingsWithRadius(ctx: IncludeSurroundingsContext) {235    const { env, selection, radius, wholeResidues, atomRadius } = ctx;236    const { model, mask } = env.context;237    const findWithin = Model.spatialLookup(model).find(mask);238    const { x, y, z } = model.positions;239    const { residueIndex } = model.atoms;240    const { atomOffset } = model.residues;241    const builder = AtomSelection.uniqueBuilder();242    const includedResides = FastSet.create<number>();243    const maxSelectionAtomRadius = maxAtomValueInSelection(env, selection, atomRadius);244    Environment.lockSlot(env, 'element');245    const element = env.slots.element;246    let maxStructureAtomRadius = 0;247    for (let i = 0, _i = model.atoms.count; i < _i; i++) {248        if (!mask.has(i)) continue;249        ElementAddress.setAtom(model, element, i);250        const r = atomRadius(env);251        if (r > maxStructureAtomRadius) maxStructureAtomRadius = r;252    }253    const extendedRadius = radius + maxSelectionAtomRadius + maxStructureAtomRadius;254    const it = AtomSetIt();255    for (const atomSet of AtomSelection.atomSets(selection)) {256        const atoms = UniqueArrayBuilder<number>();257        for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {258            const { count, indices, squaredDistances } = findWithin(x[a], y[a], z[a], extendedRadius);259            ElementAddress.setAtom(model, element, a);260            const rA = atomRadius(env);261            for (let i = 0, _i = count; i < _i; i++) {262                const b = indices[i];263                ElementAddress.setAtom(model, element, b);264                const rB = atomRadius(env);265                if (Math.sqrt(squaredDistances[i]) - rA - rB > radius) continue;266                if (wholeResidues) {267                    const rI = residueIndex[b];268                    if (includedResides.has(rI)) continue;269                    includedResides.add(rI);270                    for (let j = atomOffset[rI], _j = atomOffset[rI + 1]; j < _j; j++) {271                        if (!mask.has(j)) continue;272                        UniqueArrayBuilder.add(atoms, j, j);273                    }274                } else {275                    UniqueArrayBuilder.add(atoms, b, b);276                }277            }278        }279        builder.add(AtomSet(sortAsc(atoms.array)));280    }281    Environment.unlockSlot(env, 'element');282    return builder.getSelection();283}284export function includeSurroundings(env: Environment, params: IncludeSurroundingsParams): AtomSelection {285    const ctx: IncludeSurroundingsContext = {286        env,287        selection: params.selection(env),288        radius: params.radius(env),289        atomRadius: params.atomRadius || _zeroRadius,290        wholeResidues: params.wholeResidues ? params.wholeResidues(env) : false291    };292    if (ctx.atomRadius === _zeroRadius) {293        return includeSurroundingsNoRadius(ctx);294    } else {295        return includeSurroundingsWithRadius(ctx);296    }297}298interface ExpandConnectedCtx {299    env: Environment,300    model: Model,301    bonds: Bonds,302    mask: Mask,303    slot: BondAddress,304    test: BondTest,305    it: AtomSetIt306}307function _expandFrontierAtoms({ env, mask, bonds, test, slot }: ExpandConnectedCtx, frontier: number[], atoms: UniqueArrayBuilder<number>) {308    const newFrontier: number[] = [];309    const { neighbor, offset: bondAtomOffset, order, flags } = bonds;310    for (const a of frontier) {311        const start = bondAtomOffset[a], end = bondAtomOffset[a + 1];312        for (let i = start; i < end; i++) {313            const b = neighbor[i];314            if (mask.has(b) && testBond(env, slot, a, b, order[i], flags[i], test) && UniqueArrayBuilder.add(atoms, b, b)) newFrontier[newFrontier.length] = b;315        }316    }317    return newFrontier;318}319function _expandAtoms(ctx: ExpandConnectedCtx, atomSet: AtomSet, numLayers: number) {320    if (!numLayers) return atomSet;321    const result = UniqueArrayBuilder<number>();322    let frontier: number[] = [];323    const { it } = ctx;324    for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {325        frontier[frontier.length] = a;326    }327    for (const a of frontier) UniqueArrayBuilder.add(result, a, a);328    for (let i = 0; i < numLayers; i++) {329        frontier = _expandFrontierAtoms(ctx, frontier, result);330    }331    sortAsc(result.array);332    return AtomSet(result.array);333}334function _expandFrontierResidues({ env, model, mask, bonds, test, slot }: ExpandConnectedCtx, frontier: number[], residues: UniqueArrayBuilder<number>) {335    const newFrontier: number[] = [];336    const { neighbor, offset: bondAtomOffset, order, flags } = bonds;337    const { atomOffset } = model.residues;338    const { residueIndex } = model.atoms;339    for (const rI of frontier) {340        for (let a = atomOffset[rI], _a = atomOffset[rI + 1]; a < _a; a++) {341            if (!mask.has(a)) continue;342            const start = bondAtomOffset[a], end = bondAtomOffset[a + 1];343            for (let i = start; i < end; i++) {344                const b = neighbor[i];345                if (!mask.has(b)) continue;346                const r = residueIndex[b];347                if (testBond(env, slot, a, b, order[i], flags[i], test) && UniqueArrayBuilder.add(residues, r, r)) newFrontier[newFrontier.length] = r;348            }349        }350    }351    return newFrontier;352}353function _expandResidues(ctx: ExpandConnectedCtx, atomSet: AtomSet, numLayers: number) {354    if (!numLayers) return atomSet;355    const { atomOffset } = ctx.model.residues;356    const { residueIndex } = ctx.model.atoms;357    const residues = UniqueArrayBuilder<number>();358    let frontier: number[] = [];359    const { mask, it } = ctx360    for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {361        const rI = residueIndex[a];362        if (UniqueArrayBuilder.add(residues, rI, rI)) frontier[frontier.length] = rI;363    }364    for (let i = 0; i < numLayers; i++) {365        frontier = _expandFrontierResidues(ctx, frontier, residues);366    }367    sortAsc(residues.array);368    const atoms: number[] = [];369    for (let rI of residues.array) {370        for (let a = atomOffset[rI], _a = atomOffset[rI + 1]; a < _a; a++) {371            if (mask.has(a)) atoms[atoms.length] = a;372        }373    }374    return AtomSet(atoms);375}376export interface IncludeConnectedParams {377    selection: Selection,378    bondTest?: Expression<boolean>,379    layerCount?: Expression<number>,380    wholeResidues?: Expression<boolean>381}382export function includeConnected(env: Environment, { selection, layerCount, wholeResidues, bondTest }: IncludeConnectedParams): AtomSelection {383    const src = selection(env);384    const { model, mask } = env.context;385    const bonds = Model.bonds(model);386    const numLayers = Math.max(0, layerCount ? layerCount(env) : 1);387    const asResidues = !!wholeResidues && !!wholeResidues(env);388    const test = bondTest || defaultBondTest;389    const builder = AtomSelection.uniqueBuilder();390    Environment.lockSlot(env, 'bond');391    const ctx: ExpandConnectedCtx = {392        env,393        bonds,394        model,395        mask,396        slot: env.slots.bond,397        test,398        it: AtomSetIt()399    };400    for (const atomSet of AtomSelection.atomSets(src)) {401        if (asResidues) builder.add(_expandResidues(ctx, atomSet, numLayers));402        else builder.add(_expandAtoms(ctx, atomSet, numLayers));403    }404    Environment.unlockSlot(env, 'bond');405    return builder.getSelection();406}407export function expandProperty(env: Environment, selection: Selection, property: Expression<any>): AtomSelection {408    const { context } = env;409    const src = selection(env);410    const propertyToSetMap: FastMap<any, UniqueArrayBuilder<number>> = FastMap.create();411    Environment.lockSlot(env, 'element');412    const element = env.slots.element;413    let index = 0;414    const sets: number[][] = [];415    const it = AtomSetIt();416    for (const atomSet of AtomSelection.atomSets(src)) {417        for (let a = AtomSetIt.start(it, atomSet); !it.done; a = it.next().value) {418            ElementAddress.setAtom(context.model, element, a);419            const p = property(env);420            if (propertyToSetMap.has(p)) UniqueArrayBuilder.add(propertyToSetMap.get(p)!, index, index);421            else {422                const ub = UniqueArrayBuilder<number>();423                UniqueArrayBuilder.add(ub, index, index);424                propertyToSetMap.set(p, ub);425            }426        }427        sets[index] = [];428        index++;429    }430    const { mask } = context;431    for (let i = 0, _i = context.model.atoms.count; i < _i; i++) {432        if (!mask.has(i)) continue;433        ElementAddress.setAtom(context.model, element, i);434        const p = property(env);435        if (!propertyToSetMap.has(p)) continue;436        for (const setIndex of propertyToSetMap.get(p)!.array) sets[setIndex].push(i);437    }438    Environment.unlockSlot(env, 'element');439    const builder = AtomSelection.uniqueBuilder();440    for (const set of sets) builder.add(AtomSet(set));441    return builder.getSelection();...atom-set.ts
Source:atom-set.ts  
1/*2 * Copyright (c) 2017 MolQL contributors, licensed under MIT, See LICENSE file for more info.3 *4 * @author David Sehnal <david.sehnal@gmail.com>5 */6import { sortAsc, UniqueArrayBuilder } from '../../utils/collections'7import { Model } from '../../structure/data'8import Mask from '../../utils/mask'9type AtomSet = number | ArrayAtomSet10function AtomSet(indices: number | ArrayLike<number>): AtomSet {11    if (typeof indices === 'number') return indices;12    if (indices.length === 1) return indices[0];13    return ArrayAtomSet(indices as ReadonlyArray<number>);14}15interface ArrayAtomSet {16    atomIndices: ReadonlyArray<number>17    hashCodeComputed: boolean,18    hashCode: number,19    //hierarchy: { residueIndices: number[], chainIndices: number[], entityIndices: number[] } | undefined,20    boundingSphere: { center: [number, number, number], radius: number } | undefined21}22function ArrayAtomSet(indices: ArrayLike<number>): ArrayAtomSet {23    return {24        atomIndices: indices as ReadonlyArray<number>,25        hashCode: 0,26        hashCodeComputed: false,27        boundingSphere: void 028    };29}30namespace AtomSet {31    export interface Iterator {32        [Symbol.iterator](): Iterator,33        done: boolean;34        value: number;35        next(): { done: boolean, value: number }36        reset(atomSet: AtomSet): Iterator;37    }38    class IteratorImpl implements Iterator {39        done = true;40        value = 0;41        private atomSet: AtomSet = void 0 as any;42        private index: number = -1;43        private length: number = 0;44        [Symbol.iterator]() { return this };45        next() {46            const index = ++this.index;47            if (typeof this.atomSet === 'number') {48                this.done = this.index > 0;49            } else {50                if (index >= this.length) {51                    this.done = true;52                } else {53                    this.value = this.atomSet.atomIndices[index];54                }55            }56            return this;57        }58        reset(atomSet: AtomSet) {59            if (typeof atomSet === 'number') {60                this.value = atomSet;61                this.length = 1;62            } else {63                const ind = atomSet.atomIndices;64                this.value = ind[0];65                this.length = ind.length;66            }67            this.done = false;68            this.atomSet = atomSet;69            this.index = -1;70            return this;71        }72    }73    export function Iterator(): Iterator { return new IteratorImpl(); }74    export namespace Iterator {75        export function start(it: Iterator, atomSet: AtomSet) { return it.reset(atomSet).next().value; }76    }77    export function count(a: AtomSet) {78        return typeof a === 'number' ? 1 : a.atomIndices.length;79    }80    export function toIndices(a: AtomSet): ReadonlyArray<number> {81        return typeof a === 'number' ? [a] : a.atomIndices;82    }83    export function getMask(a: AtomSet) {84        return typeof a === 'number' ? Mask.singleton(a) : Mask.ofUniqueIndices(a.atomIndices);85    }86    const itA = Iterator(), itB = Iterator();87    export function areEqual(a: AtomSet, b: AtomSet) {88        const cnt = count(a);89        if (cnt !== count(b)) return false;90        Iterator.start(itA, a);91        Iterator.start(itB, b);92        for (let i = 0; i < cnt; i++) {93            if (itA.value !== itB.value) return false;94            itA.next();95            itB.next();96        }97        return true;98    }99    export function ofUnsortedIndices(indices: number[]): AtomSet {100        return AtomSet(sortAsc(indices));101    }102    export function atomDistanceSq(x: number[], y: number[], z: number[], i: number, j: number) {103        const dx = x[i] - x[j], dy = y[i] - y[j], dz = z[i] - z[j];104        return dx * dx + dy * dy + dz * dz;105    }106    function computeHashCode(atomSet: ArrayAtomSet) {107        let code = 23;108        for (const i of atomSet.atomIndices) {109            code = (31 * code + i) | 0;110        }111        atomSet.hashCode = code;112        atomSet.hashCodeComputed = true;113        return code;114    }115    export function hashCode(atomSet: AtomSet) {116        if (typeof atomSet === 'number') return atomSet;117        if (atomSet.hashCodeComputed) return atomSet.hashCode!;118        return computeHashCode(atomSet);119    }120    export function hierarchy(model: Model, atomSet: AtomSet) {121        const residueIndices = UniqueArrayBuilder<number>();122        const chainIndices = UniqueArrayBuilder<number>();123        const entityIndices = UniqueArrayBuilder<number>();124        const rIndices = model.atoms.residueIndex;125        const cIndices = model.residues.chainIndex;126        const eIndices = model.chains.entityIndex;127        const it = Iterator();128        for (let i = Iterator.start(it, atomSet); !it.done; i = it.next().value) { UniqueArrayBuilder.add(residueIndices, rIndices[i], rIndices[i]); }129        for (const i of residueIndices.array) { UniqueArrayBuilder.add(chainIndices, cIndices[i], cIndices[i]); }130        for (const i of chainIndices.array) { UniqueArrayBuilder.add(entityIndices, eIndices[i], eIndices[i]); }131        return { residueIndices: residueIndices.array, chainIndices: chainIndices.array, entityIndices: entityIndices.array };132    }133    function computeBoundingSphere(model: Model, atomSet: ArrayAtomSet) {134        const { x, y, z } = model.positions;135        if (atomSet.atomIndices.length === 1) {136            const i = atomSet.atomIndices[0];137            atomSet.boundingSphere = { center: [x[i], y[i], z[i]], radius: 0 };138            return atomSet.boundingSphere;139        }140        const center: [number, number, number] = [0, 0, 0];141        for (const i of atomSet.atomIndices) {142            center[0] += x[i];143            center[1] += y[i];144            center[2] += z[i];145        }146        center[0] *= 1 / atomSet.atomIndices.length;147        center[1] *= 1 / atomSet.atomIndices.length;148        center[2] *= 1 / atomSet.atomIndices.length;149        let radius = 0;150        for (const i of atomSet.atomIndices) {151            const dx = center[0] - x[i], dy = center[1] - y[i], dz = center[2] - z[i];152            radius = Math.max(dx * dx + dy * dy + dz * dz, radius);153        }154        atomSet.boundingSphere = { center, radius };155        return atomSet.boundingSphere;156    }157    export function boundingSphere(model: Model, atomSet: AtomSet) {158        if (typeof atomSet === 'number') {159            const { x, y, z } = model.positions;160            return { center: [x[atomSet], y[atomSet], z[atomSet]], radius: 0 };161        }162        if (atomSet.boundingSphere) return atomSet.boundingSphere;163        return computeBoundingSphere(model, atomSet);164    }165    export function distance(model: Model, a: AtomSet, b: AtomSet) {166        if (a === b) return 0;167        let distSq = Number.POSITIVE_INFINITY;168        const { x, y, z } = model.positions;169        for (let i = Iterator.start(itA, a); !itA.done; i = itA.next().value) {170            for (let j = Iterator.start(itB, b); !itB.done; j = itB.next().value) {171                const d = atomDistanceSq(x, y, z, i, j);172                if (d < distSq) distSq = d;173            }174        }175        return Math.sqrt(distSq);176    }177    export function areWithin(model: Model, a: AtomSet, b: AtomSet, maxDistance: number) {178        if (a === b) return true;179        const dSq = maxDistance * maxDistance;180        const { x, y, z } = model.positions;181        for (let i = Iterator.start(itA, a); !itA.done; i = itA.next().value) {182            for (let j = Iterator.start(itB, b); !itB.done; j = itB.next().value) {183                if (atomDistanceSq(x, y, z, i, j) <= dSq) return true;184            }185        }186        return false;187    }188    export function union(a: AtomSet, b: AtomSet): AtomSet {189        const la = count(a), lb = count(b);190        let i = 0, j = 0, resultSize = 0;191        Iterator.start(itA, a);192        Iterator.start(itB, b);193        while (i < la && j < lb) {194            const x = itA.value, y = itB.value;195            resultSize++;196            if (x < y) { itA.next(); i++; }197            else if (x > y) { itB.next(); j++; }198            else { i++; j++; itA.next(); itB.next(); }199        }200        resultSize += Math.max(la - i, lb - j);201        const indices = new Int32Array(resultSize);202        let offset = 0;203        i = 0;204        j = 0;205        Iterator.start(itA, a);206        Iterator.start(itB, b);207        while (i < la && j < lb) {208            const x = itA.value, y = itB.value;209            resultSize++;210            if (x < y) { indices[offset++] = x; i++; itA.next(); }211            else if (x > y) { indices[offset++] = y; j++; itB.next(); }212            else { indices[offset++] = x; i++; j++; itA.next(); itB.next();  }213        }214        for (; i < la; i++) { indices[offset++] = itA.value; itA.next(); }215        for (; j < lb; j++) { indices[offset++] = itB.value; itB.next(); }216        return AtomSet(indices);217    }218}...collections.ts
Source:collections.ts  
1/*2 * Copyright (c) 2017 MolQL contributors, licensed under MIT, See LICENSE file for more info.3 *4 * @author David Sehnal <david.sehnal@gmail.com>5 */6export interface UniqueArrayBuilder<T> { _keys: any, array: T[] }7export function UniqueArrayBuilder<T>(): UniqueArrayBuilder<T> { return { _keys: Object.create(null), array: [] } }8export namespace UniqueArrayBuilder {9    export function add<T>({ _keys, array }: UniqueArrayBuilder<T>, key: string | number, value: any) {10        if (_keys[key] === 1) return false;11        _keys[key] = 1;12        array.push(value);13        return true;14    }15}16function _ascSort(a: number, b: number) {17    return a - b;18}19export function sortAsc<T extends ArrayLike<number>>(array: T): T {20    Array.prototype.sort.call(array, _ascSort);21    return array;22}23/**24 * An "object" based implementation of map that supports string and numeric keys25 * which should be ok for most use cases in LiteMol.26 *27 * The type limitation is on purpose to prevent using the type in places that are28 * not appropriate.29 */30export interface FastMap<K extends string | number, V> {31    readonly size: number;32    set(key: K, v: V): void;33    get(key: K): V | undefined;34    delete(key: K): boolean;35    has(key: K): boolean;36    clear(): void;37    /**38     * Iterate over the collection.39     * Optional "context" object can be supplied that is passed to the callback.40     *41     * Enumerates only values that are not undefined.42     */43    forEach<Context>(f: (value: V, key: K, ctx?: Context) => void, ctx?: Context): void;44}45/**46 * An "object" based implementation of set that supports string and numeric values47 * which should be ok for most use cases in LiteMol.48 *49 * The type limitation is on purpose to prevent using the type in places that are50 * not appropriate.51 */52export interface FastSet<T extends string | number> {53    readonly size: number;54    add(key: T): boolean;55    delete(key: T): boolean;56    has(key: T): boolean;57    clear(): void;58    /**59     * Iterate over the collection.60     * Optional "context" object can be supplied that is passed to the callback.61     */62    forEach<Context>(f: (key: T, ctx?: Context) => boolean | any, ctx?: Context): void;63}64function createMapObject() {65    const map = Object.create(null);66    // to cause deoptimization as we don't want to create hidden classes67    map['__'] = void 0;68    delete map['__'];69    return map;70}71type MapData = { data: any, size: number }72export namespace FastMap {73    function forEach(data: any, f: (value: any, key: any, ctx: any) => void, ctx: any) {74        for (const key of Object.keys(data)) {75            const v = data[key];76            if (v === void 0) continue;77            f(v, key, ctx);78        }79    }80    const fastMap = {81        set(this: MapData, key: string | number, v: any) {82            if (this.data[key] === void 0 && v !== void 0) {83                this.size++;84            }85            this.data[key] = v;86        },87        get(this: MapData, key: string | number) {88            return this.data[key];89        },90        delete(this: MapData, key: string | number) {91            if (this.data[key] === void 0) return false;92            delete this.data[key];93            this.size--;94            return true;95        },96        has(this: MapData, key: string | number) {97            return this.data[key] !== void 0;98        },99        clear(this: MapData) {100            this.data = createMapObject();101            this.size = 0;102        },103        forEach(this: MapData, f: (k: string | number, v: number, ctx?: any) => void, ctx?: any) {104            forEach(this.data, f, ctx !== void 0 ? ctx : void 0);105        }106    };107    /**108     * Creates an empty map.109     */110    export function create<K extends string | number, V>(): FastMap<K, V> {111        const ret = Object.create(fastMap) as any;112        ret.data = createMapObject();113        ret.size = 0;114        return ret;115    }116    /**117     * Create a map from an array of the form [[key, value], ...]118     */119    export function ofArray<K extends string | number, V>(data: [K, V][]) {120        const ret = create<K, V>();121        for (const xs of data) {122            ret.set(xs[0] as K, xs[1] as V);123        }124        return ret;125    }126    /**127     * Create a map from an object of the form { key: value, ... }128     */129    export function ofObject<V>(data: { [key: string]: V }) {130        const ret = create<string, V>();131        for (const key of Object.keys(data)) {132            const v = data[key];133            ret.set(key, v);134        }135        return ret;136    }137}138export namespace FastSet {139    function forEach(data: any, f: (k: string | number, ctx: any) => boolean | void, ctx: any) {140        for (const p of Object.keys(data)) {141            if (data[p] !== null) continue;142            if (f(p, ctx) === false) break;143        }144    }145    /**146     * Uses null for present values.147     */148    const fastSet = {149        add(this: MapData, key: string | number) {150            if (this.data[key] === null) return false;151            this.data[key] = null;152            this.size++;153            return true;154        },155        delete(this: MapData, key: string | number) {156            if (this.data[key] !== null) return false;157            delete this.data[key];158            this.size--;159            return true;160        },161        has(this: MapData, key: string | number) {162            return this.data[key] === null;163        },164        clear(this: MapData) {165            this.data = createMapObject();166            this.size = 0;167        },168        forEach(this: MapData, f: (k: string | number, ctx: any) => void, ctx?: any) {169            forEach(this.data, f, ctx !== void 0 ? ctx : void 0);170        }171    };172    /**173     * Create an empty set.174     */175    export function create<T extends string | number>(): FastSet<T> {176        const ret = Object.create(fastSet) as any;177        ret.data = createMapObject();178        ret.size = 0;179        return ret;180    }181    /**182     * Create a set of an "array like" sequence.183     */184    export function ofArray<T extends string | number>(xs: ArrayLike<T>) {185        const ret = create<T>();186        for (let i = 0, l = xs.length; i < l; i++) {187            ret.add(xs[i]);188        }189        return ret;190    }191    export function isSubset<T extends string | number>(a: FastSet<T>, b: FastSet<T>) {192        const _ctx = { b, count: 0 };193        a.forEach((e, ctx) => {194            if (!ctx!.b.has(e)) return false;195            ctx!.count++;196        }, _ctx);197        return _ctx.count === a.size;198    }...Using AI Code Generation
1const { uniqueArrayBuilder } = require("fast-check-monorepo");2console.log(uniqueArrayBuilder(10));3{4  "scripts": {5  },6  "dependencies": {7  }8}Using AI Code Generation
1const { uniqueArrayBuilder } = require('fast-check-monorepo');2const array = uniqueArrayBuilder().build();3console.log(array);4{5  "scripts": {6  },7  "dependencies": {8  }9}10const array = uniqueArrayBuilder({minSize: 1, maxSize: 5, minUniqueItems: 1, maxUniqueItems: 5}).build();11The uniqueArrayBuilder() method can also be used to build an array of a specific type. For example, the following code will build an array of strings:12const array = uniqueArrayBuilder().of(string()).build();13The uniqueArrayBuilder() method can also be used to build an array of a specific type and with a specific set of settings. For example, the following code will build an array of strings with a minimum size of 1, a maximum size of 5, a minimum of 1 unique item, and a maximum of 5 unique items:14const array = uniqueArrayBuilder({minSize: 1, maxSize: 5, minUniqueItems: 1, maxUniqueItems: 5}).of(string()).build();15The uniqueArrayBuilder() method can also be used to build an array ofUsing AI Code Generation
1const { uniqueArrayBuilder } = require('fast-check-monorepo');2const { uniqueArrayBuilder } = require('fast-check');3const uniqueArray = uniqueArrayBuilder(100);4console.log(uniqueArray(10));5const { uniqueArrayBuilder } = require('fast-check');6const uniqueArray = uniqueArrayBuilder(100);7console.log(uniqueArray(10));Using AI Code Generation
1const uniqueArrayBuilder = require('fast-check-monorepo/dist/lib/check/arbitrary/uniqueArrayBuilder').uniqueArrayBuilder;2const uniqueArrayBuilder1 = require('fast-check-monorepo').uniqueArrayBuilder;3const fc = require('fast-check');4const { uniqueArrayBuilder } = require('fast-check-monorepo');5console.log('uniqueArrayBuilder: ', uniqueArrayBuilder);6const uniqueArrayArb = uniqueArrayBuilder(fc.integer(), 0, 1);7fc.assert(fc.property(uniqueArrayArb, (uniqueArray) => {8  const uniqueArraySet = new Set(uniqueArray);9  return uniqueArray.length === uniqueArraySet.size;10}));11console.log('uniqueArrayBuilder: ', uniqueArrayBuilder);12const uniqueArrayArb1 = uniqueArrayBuilder1(fc.integer(), 0, 1);13fc.assert(fc.property(uniqueArrayArb1, (uniqueArray) => {14  const uniqueArraySet = new Set(uniqueArray);15  return uniqueArray.length === uniqueArraySet.size;16}));17console.log('uniqueArrayBuilder: ', uniqueArrayBuilder);18const uniqueArrayArb2 = uniqueArrayBuilder(fc.integer(), 0, 1);19fc.assert(fc.property(uniqueArrayArb2, (uniqueArray) => {20  const uniqueArraySet = new Set(uniqueArray);21  return uniqueArray.length === uniqueArraySet.size;22}));Using AI Code Generation
1const { uniqueArrayBuilder } = require('fast-check');2const { array } = require('fast-check');3const uniqueArray = uniqueArrayBuilder(array);4console.log(uniqueArray().generate());5at Object.<anonymous> (C:\Users\test.js:3:26)6at Module._compile (internal/modules/cjs/loader.js:1137:30)7at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)8at Module.load (internal/modules/cjs/loader.js:986:32)9at Function.Module._load (internal/modules/cjs/loader.js:879:14)10at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)11const { uniqueArrayBuilder } = require('fast-check-monorepo');12const { array } = require('fast-check-monorepo');13const uniqueArray = uniqueArrayBuilder(array);Using AI Code Generation
1const uniqueArrayBuilder = require("fast-check-monorepo").uniqueArrayBuilder;2const uniqueArray = uniqueArrayBuilder(array, array.length);3const uniqueArrayBuilder = require("fast-check-monorepo").uniqueArrayBuilder;4const uniqueArray = uniqueArrayBuilder(array, array.length);5const uniqueArrayBuilder = require("fast-check-monorepo").uniqueArrayBuilder;6const uniqueArray = uniqueArrayBuilder(array, array.length);7const uniqueArrayBuilder = require("fast-check-monorepo").uniqueArrayBuilder;8const uniqueArray = uniqueArrayBuilder(array, array.length);9const uniqueArrayBuilder = require("fast-check-monorepo").uniqueArrayBuilder;10const uniqueArray = uniqueArrayBuilder(array, array.length);11const uniqueArrayBuilder = require("fast-check-monorepo").uniqueArrayBuilder;12const uniqueArray = uniqueArrayBuilder(array, array.length);13const uniqueArrayBuilder = require("fast-check-monorepo").uniqueArrayBuilder;14const uniqueArray = uniqueArrayBuilder(array, array.length);15const uniqueArrayBuilder = require("fast-check-monorepo").uniqueArrayBuilder;16const uniqueArray = uniqueArrayBuilder(array, array.length);17const uniqueArrayBuilder = require("fastLearn 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!!
