All files / src/parsers CDJSON.ts

97.36% Statements 37/38
71.42% Branches 10/14
100% Functions 1/1
97.22% Lines 35/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                      1x 1x   1x   1x 1x 1x   1x   1x       1x     1x 4x 4x 4x   4x 4x 4x   4x 4x   4x 4x   4x 4x     4x   1x 3x 3x 3x 3x   3x 3x   3x 3x 3x 3x   1x    
/** 
 * This parses the ChemDoodle json file format. Although this is registered
 * for the json file extension, other chemical json file formats exist that
 * this can not parse. Check which one you have and do not assume that
 * .json can be parsed
 * 
 * @param {string} str
 * @param {ParserOptionsSpec} options
 * @category Parsers
 */
export function CDJSON(str, options) {
  var atoms: any[][] & Record<string, any> = [[]];
  if (typeof str === "string") {
    // Str is usually automatically parsed by JQuery
    str = JSON.parse(str);
  }
  var molecules = str.m;
  var atomsInFile = molecules[0].a; // Assumes there is at least one
  var bondsInFile = molecules[0].b; // molecule and ignores any more
  // Ignores any shapes
  var styles = molecules[0].s;
  var parseStyle =
    options !== undefined && options.parseStyle !== undefined
      ? options.parseStyle
      : styles !== undefined;
 
  var offset = atoms[atoms.length - 1].length; // When adding atoms their index will be
  // Offset by the number of existing atoms
 
  for (var i = 0; i < atomsInFile.length; i++) {
    var currentAtom = atomsInFile[i];
    var atom: Record<string, any> = {};
    atom.id = currentAtom.i; // Probably won't exist. Doesn't seem to
    // break anything.
    atom.x = currentAtom.x;
    atom.y = currentAtom.y;
    atom.z = currentAtom.z || 0; // Default value if file is 2D
 
    atom.bonds = [];
    atom.bondOrder = [];
 
    var elem = currentAtom.l || "C";
    atom.elem = elem[0].toUpperCase() + elem.substr(1).toLowerCase();
 
    atom.serial = atoms[atoms.length - 1].length;
    Iif (parseStyle) {
      atom.style = styles[currentAtom.s || 0];
    }
    atoms[atoms.length - 1].push(atom);
  }
  for (let i = 0; i < bondsInFile.length; i++) {
    let currentBond = bondsInFile[i];
    let beginIndex = currentBond.b + offset;
    let endIndex = currentBond.e + offset;
    let bondOrder = currentBond.o || 1;
 
    let firstAtom = atoms[atoms.length - 1][beginIndex];
    let secondAtom = atoms[atoms.length - 1][endIndex];
 
    firstAtom.bonds.push(endIndex);
    firstAtom.bondOrder.push(bondOrder);
    secondAtom.bonds.push(beginIndex);
    secondAtom.bondOrder.push(bondOrder);
  }
  return atoms;
}