1. /**
  2. * Aggregates configuration values from an array of configuration objects.
  3. *
  4. * @param {Array<object>} configurations An array of configuration objects. Each object
  5. * is expected to have a 'name' property (string)
  6. * and a 'value' property (number).
  7. * @returns {object} An object where keys are configuration names and values are
  8. * the sum of their corresponding values. Returns an empty object
  9. * if the input array is empty or invalid.
  10. */
  11. function aggregateConfigurations(configurations) {
  12. if (!Array.isArray(configurations) || configurations.length === 0) {
  13. return {}; // Handle empty or invalid input
  14. }
  15. const aggregatedValues = {};
  16. for (const config of configurations) {
  17. if (typeof config !== 'object' || config === null || !config.hasOwnProperty('name') || !config.hasOwnProperty('value')) {
  18. continue; // Skip invalid configuration entries
  19. }
  20. const name = config.name;
  21. const value = Number(config.value); //Convert value to number
  22. if (isNaN(value)) {
  23. continue; // Skip if value is not a number
  24. }
  25. if (aggregatedValues.hasOwnProperty(name)) {
  26. aggregatedValues[name] += value;
  27. } else {
  28. aggregatedValues[name] = value;
  29. }
  30. }
  31. return aggregatedValues;
  32. }

Add your comment