File: lib/util/obj.js

Recommend this page to a friend!
  Classes of Harcharan Singh  >  Node Input Validator  >  lib/util/obj.js  >  Download  
File: lib/util/obj.js
Role: Example script
Content type: text/plain
Description: Example script
Class: Node Input Validator
Validate submitted input values in Node.js
Author: By
Last change: support to for locale or options to validator in alpha, alphaNumeric, phoneNumber and str notation repetition limit of now flexible
Date: 1 month ago
Size: 1,276 bytes
 

Contents

Class file image Download
let wildcardIterations = 1000;


function esc(key, options) {
  if (typeof options.escape === 'function') {
    return options.escape(key, options);
  }
  return key.split(options.separator).join(`\\${options.separator}`);
}

exports.setStrNotationRepetition = (repetition) => wildcardIterations = repetition;

exports.strNotations = function strNotations(target, customize = {}) {
  const options = {
    separator: '.',
    repetition: wildcardIterations,
    values: true,
    ...customize,
  };
  const sep = options.separator;
  const values = {};
  const keys = [];

  let currentRep = 0;

  function parse(obj, prev) {
    currentRep++;

    if (currentRep >= options.repetition) {
      // eslint-disable-next-line no-console
      throw new Error(`Max(${options.repetition}) repetation was reached.`);
    }

    const objKeys = Object.keys(obj);

    objKeys.forEach((k) => {
      const val = obj[k];
      const key = (prev ? prev + sep : '') + esc(k, options);

      if (Array.isArray(val) || (val !== null && typeof val === 'object')) {
        parse(val, key);
        keys.push(key);
        values[key] = val;
      } else {
        keys.push(key);
        values[key] = val;
      }
    });
  }

  parse(target);
  return options.values ? values : keys;
};