How to use flat - 10 common examples

To help you get started, we’ve selected a few flat examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github appirio-tech / connect-app / src / helpers / wizardHelper.js View on Github external
export const buildProjectUpdateQueryByQueryParamSelectCondition = (template, queryParams) => {
  /**
   * Supported types of questions
   */
  const TYPE = {
    CHECKBOX_GROUP: 'checkbox-group',
    RADIO_GROUP: 'radio-group',
  }
  const prefillData = {}
  const updateQuery = { $merge: prefillData }
  const flatQueryParams = flatten(queryParams, { safe: true })

  forEachNode(template, (nodeObject, node) => {
    if (
      // if condition is defined
      nodeObject.queryParamSelectCondition &&
      // support only for `options` nodes
      isNodeLevel(node, LEVEL.OPTION) &&
      // if condition is satisfied
      evaluate(nodeObject.queryParamSelectCondition, flatQueryParams)
    ) {
      const questionNode = getParentNode(node)
      const questionNodeObject = getNodeObject(template, questionNode)

      if (!questionNodeObject.fieldName) {
        console.error('Question of the option with "queryParamSelectCondition" doesn\'t have "fieldName". So we cannot pre-fill data.')
        return
github kvz / metriks / lib / plugin.js View on Github external
)));
    }

    // Parse comment header
    var flat         = {};
    var commentLines = stdout.match(/^#(.*)$/img);
    if (commentLines && commentLines.length) {
      commentLines.forEach(function(line) {
        var cfgKey   = line.match(/^#\s*([^:]+)\s*/)[1];
        var cfgVal   = line.match(/:\s*(.*)\s*$/)[1];
        flat[cfgKey] = cfgVal;
      });
    }

    // Convert flat -> structure to recursive
    var nested = unflatten(flat, {
      delimiter: '->',
      object   : true,
    });

    // Apply defaults to said config
    _.extend(self, self.defaultConfig, nested.config);

    // Fixed plugin options
    self.name       = path.basename(self.pluginFile, '.sh');
    self.executable = !!(1 & parseInt ((fs.statSync(self.pluginFile).mode & parseInt('777', 8)).toString(8)[0]));

    if (self.enabled === 'false') {
      self.enabled = false;
    } else {
      self.enabled = true;
    }
github jondot / storybook-cartesian / dist / index.js View on Github external
        const rows = fp.map(p => flatten.unflatten(fp.fromPairs(fp.zip(fields, p))), xproduct(fp.map(v => (isChoice(v) ? nodeValue(v) : [v]), fp.values(compiledData))));
        // filter rows (remove empty and nonvalid)
github Boulangerie / angular-translate-extract / lib / translations.js View on Github external
// Feed empty translation (null or "")
        returnTranslations[k] = self.params.nullEmpty ? null : "";
      }
    });
  }

  if (!_.isUndefined(useDefault) && useDefault) {
    returnTranslations = this.getDefaultTranslations(returnTranslations);
  }

  this.computeStats(obj, translations, returnTranslations);

  // Case namespace (tree representation)
  if (this.params.tree) {
    // We need to remove parent NS
    returnTranslations = flat.unflatten(Translations.cleanParents(returnTranslations));
  }

  return returnTranslations;
};
github LessWrong2 / Lesswrong2 / packages / vulcan-lib / lib / modules / settings.js View on Github external
export const getAllSettings = () => {

  const settingsObject = {};

  let rootSettings = _.clone(Meteor.settings);
  delete rootSettings.public;
  delete rootSettings.private;

  // root settings & private settings are both private
  rootSettings = flatten(rootSettings, {safe: true});
  const privateSettings = flatten(Meteor.settings.private || {}, {safe: true});

  // public settings
  const publicSettings = flatten(Meteor.settings.public || {}, {safe: true});

  // registered default values
  const registeredSettings = Settings;

  const allSettingKeys = _.union(_.keys(rootSettings), _.keys(publicSettings), _.keys(privateSettings), _.keys(registeredSettings));

  allSettingKeys.sort().forEach(key => {

    settingsObject[key] = {};

    if (typeof rootSettings[key] !== 'undefined') {
      settingsObject[key].value = rootSettings[key];
    } else if (typeof privateSettings[key] !== 'undefined') {
      settingsObject[key].value = privateSettings[key];
    } else if (typeof publicSettings[key] !== 'undefined') {
      settingsObject[key].value = publicSettings[key];
github akameco / extract-react-intl-messages / src / index.ts View on Github external
const file = path.resolve(buildDir, `${locale}.${ext}`)
    // Initialize json file
    try {
      const output = isJson(ext) ? JSON.stringify({}) : yaml.safeDump({})
      fs.writeFileSync(file, output, { flag: 'wx' })
    } catch (error) {
      if (error.code !== 'EEXIST') {
        throw error
      }
    }

    let messages = isJson(ext)
      ? loadJsonFile.sync(file)
      : yaml.safeLoad(fs.readFileSync(file, 'utf8'), { json: true })

    messages = flatten(messages)

    oldLocaleMaps[locale] = {}
    for (const messageKey of Object.keys(messages)) {
      const message = messages[messageKey]
      if (message && typeof message === 'string' && message !== '') {
        oldLocaleMaps[locale][messageKey] = messages[messageKey]
      }
    }
  }

  return oldLocaleMaps
}
github iopipe / iopipe-js-trace / src / plugins / https.js View on Github external
// setup http trace data that will be sent to IOpipe later
      moduleData[id] = {};
      moduleData[id].request = getReqDataObject(rawOptions, protocol);
      // patch for Axios
      if (!moduleData[id].request.hostname && moduleData[id].request.host) {
        moduleData[id].request.hostname = moduleData[id].request.host;
      } else if (
        !moduleData[id].request.hostname &&
        moduleData[id].request.url
      ) {
        moduleData[id].request.hostname = moduleData[id].request.url;
      }

      // flattening so that req headers can be sent even if there's a timeout
      moduleData[id] = flatten(moduleData[id], { maxDepth: 5 });
      moduleData[id] = filterData(config, moduleData[id]);

      // the func to execute at the end of the http call
      function extendedCallback(res) {
        timeline.mark(`end:${id}`);
        // add full response data if the request passed filtering
        if (typeof moduleData[id] === 'object') {
          moduleData[id].response = getResDataObject(res);
          // flatten object for easy transformation/filtering later
          moduleData[id] = flatten(moduleData[id], { maxDepth: 5 });
          moduleData[id] = filterData(config, moduleData[id]);
        }

        // if either filter function returns falsey value, drop all data completely
        if (typeof moduleData[id] !== 'object') {
          timeline.data = timeline.data.filter(
github commercetools / nodejs / packages / discount-code-exporter / src / main.js View on Github external
// fields if empty and they are not correctly written to the CSV file
    const objKeys = [
      'attributeTypes',
      'cartFieldTypes',
      'lineItemFieldTypes',
      'customLineItemFieldTypes',
    ]

    const discountCodeData = Object.entries(restDiscountCodeData).reduce(
      (discountCode: Object, [discountCodeKey, value]: [string, any]): Object =>
        objKeys.includes(discountCodeKey) && !Object.entries(value).length
          ? discountCode
          : { ...discountCode, [discountCodeKey]: value },
      {}
    )
    return flatten({
      ...discountCodeData,
      cartDiscounts: cartDiscountsString,
      groups: groupsString,
    })
  }
}
github oreqizer / redux-forms / packages / redux-forms / src / __tests__ / arrays.spec.ts View on Github external
it('should not shift to negative index', () => {
    const res = arrayShift('flat', 0)(fields);

    expect(res['flat.-1']).toBeUndefined();

    expect(res['flat.0']).toBe(field1);
    expect(res['flat.1']).toBe(field2);
    expect(res['flat.2']).toBe(field3);
    expect(res['flat.3']).toBe(field4);
  });
github oreqizer / redux-forms / packages / redux-forms / src / __tests__ / arrays.spec.ts View on Github external
it('should shift flat array', () => {
    const res = arrayUnshift('flat', 1)(fields);

    expect(res['flat.1']).toBeUndefined();

    expect(res['flat.0']).toBe(field0);
    expect(res['flat.2']).toBe(field1);
    expect(res['flat.3']).toBe(field2);
    expect(res['flat.4']).toBe(field3);
    expect(res['flat.5']).toBe(field4);
  });

flat

Take a nested Javascript object and flatten it, or unflatten an object with delimited keys

BSD-3-Clause
Latest version published 1 year ago

Package Health Score

80 / 100
Full package analysis