1. /**
  2. * Attaches metadata to arrays for sandbox usage based on a configuration file.
  3. *
  4. * @param {Array<any>} arr The array to attach metadata to.
  5. * @param {object} config The configuration object containing metadata definitions.
  6. * @param {function} getArrayMetadata A function to retrieve the original array.
  7. */
  8. function attachArrayMetadata(arr, config, getArrayMetadata) {
  9. if (!Array.isArray(arr)) {
  10. console.warn("Input is not an array.");
  11. return;
  12. }
  13. if (!config || typeof config !== 'object') {
  14. console.warn("Configuration is not a valid object.");
  15. return;
  16. }
  17. for (let i = 0; i < arr.length; i++) {
  18. const item = arr[i];
  19. //Check if the item is an array
  20. if (Array.isArray(item)) {
  21. const metadata = config[item.length === 0 ? 'default' : item.length]; // Get metadata for the array length. Added default case for empty array.
  22. if (metadata) {
  23. // Attach metadata to the array
  24. Object.assign(item, metadata);
  25. }
  26. }
  27. }
  28. }
  29. // Example Usage (assuming you have a config file loaded)
  30. // const config = {
  31. // 0: { description: "First element", type: "string" },
  32. // 1: { description: "Second element", type: "number" },
  33. // 2: { description: "Third element", type: "boolean" },
  34. // default: {description: "Default element", type: "any"}
  35. // };
  36. // const myArray = [1, "hello", true];
  37. // attachArrayMetadata(myArray, config);
  38. // const myOtherArray = [];
  39. // attachArrayMetadata(myOtherArray, config);

Add your comment