Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@doodle/i18n / dist / processMessages.js
Size: Mime:
/**
 * Reduce messages JSON object.
 *
 * Input:
 * {
 *   "billing.components.App.doodle": "Doodle"
 *   "billing.components.App.pricing": "Pricing"
 * }
 *
 * Output:
 * {
 *   billing: {
 *     components: {
 *       App: {
 *         doodle: "Doodle",
 *         pricing": "Pricing"
 *       }
 *     }
 *   }
 * }
 */
const reduce = messages => {
  const result = {};

  Object.entries(messages).forEach(([key, value]) => {
    const steps = key.split('.');
    let next = result;

    steps.forEach((step, index) => {
      next[step] = next[step] || (index < steps.length - 1 ? {} : value);
      next = next[step];
    });
  });

  return result;
};

/**
 * Normalize messages JSON object.
 *
 * Input:
 * {
 *   billing: {
 *     components: {
 *       App: {
 *         doodle: "Doodle",
 *         pricing": "Pricing"
 *       }
 *     }
 *   }
 * }
 *
 * Output:
 * {
 *   "billing.components.App.doodle": "Doodle"
 *   "billing.components.App.pricing": "Pricing"
 * }
 */
const normalizeRec = (path, acc, result) => {
  Object.entries(acc).forEach(([key, value]) => {
    const nextKey = `${path ? `${path}.` : ''}${key}`;
    if (typeof value === 'string') {
      result[nextKey] = value;
    } else {
      normalizeRec(nextKey, value, result);
    }
  });
};

const normalize = messages => {
  const result = {};
  normalizeRec('', messages, result);
  return result;
};

/**
 * Export
 */
module.exports = {
  reduce,
  normalize,
};