All files / parsers json.js

100% Statements 39/39
100% Branches 19/19
100% Functions 6/6
100% Lines 34/34

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 641x       800x 800x   800x 400x 400x 400x   400x     400x 400x 400x 400x   400x             400x   400x   400x 359x   310x 1887x 310x     400x       800x 800x 800x   800x 2762x   2762x 2762x 663x   2099x 2099x 2099x 2099x       800x    
module.exports = {
  name: 'json',
  desc: 'parses each token into JSON, but fails all tokens if an error is thrown:\n\n--no-bulk, -B [boolean]\nDeactivates bulk parsing, which is much slower, but fails only those tokens that throw an error.\n',
  func: ({B, noBulk, verbose}) => {
    const _noBulk     = noBulk || B || false
    const parseTokens = tokensParser({verbose})
  
    if (_noBulk) {
      return (tokens, lines) => {
        const _lines       = verbose > 0 ? lines : []
        const {jsons, err} = parseTokens(tokens, _lines)
  
        return {jsons, err}
      }
    } else {
      return (tokens, lines) => {
        const _lines       = verbose > 0 ? lines : []
        const {jsons, err} = parseTokens(concatTokens(tokens), _lines)
        const jsons2       = typeof jsons[0] !== 'undefined' ? jsons[0] : []
 
        return {jsons: jsons2, err}
      }
    }
  }
}
 
function concatTokens (tokens) {
  let str = '['
 
  const tokensLen = tokens.length
 
  if (tokensLen === 0) str += ']'
  else if (tokensLen === 1) str += tokens[0] + ']'
  else {
    str += tokens[0]
    for (let index = 1; index < tokensLen; index++) str += ',' + tokens[index]
    str += ']'
  }
 
  return [str]
}
 
function tokensParser ({verbose}) {
  return (tokens, lines) => {
    const jsons = []
    const err   = []
  
    for (let index = 0; index < tokens.length; index++) {
      const token = tokens[index]
  
      try {
        const obj = JSON.parse(token)
        jsons.push(obj)
      } catch (e) {
        const msg  =               {msg:  e.message}
        const line = verbose > 0 ? {line: lines[index]} : {}
        const info = verbose > 1 ? {info: token}        : {}
        err.push(Object.assign(msg, line, info))
      }
    }
  
    return {err, jsons}
  }
}