util.mjs 1.2 KB

123456789101112131415161718192021222324252627282930
  1. /*---------------------------------------------------------
  2. * Copyright (C) Microsoft Corporation. All rights reserved.
  3. *--------------------------------------------------------*/
  4. import { promises as fs } from 'fs';
  5. export const ensureArray = (value) => (Array.isArray(value) ? value : [value]);
  6. export const readJSON = async (path) => JSON.parse(await fs.readFile(path, 'utf8'));
  7. export const writeJSON = async (path, value) => fs.writeFile(path, JSON.stringify(value));
  8. /**
  9. * Applies the "replacer" function to primitive keys and properties of the object,
  10. * mutating it in-place.
  11. */
  12. export const mutateObjectPrimitives = (obj, replacer) => {
  13. if (Array.isArray(obj)) {
  14. for (let i = 0; i < obj.length; i++) {
  15. obj[i] = mutateObjectPrimitives(obj[i], replacer);
  16. }
  17. return obj;
  18. }
  19. if (obj && typeof obj === 'object') {
  20. for (const [key, value] of Object.entries(obj)) {
  21. const newKey = replacer(key);
  22. if (newKey !== key) {
  23. delete obj[key];
  24. }
  25. obj[newKey] = mutateObjectPrimitives(value, replacer);
  26. }
  27. return obj;
  28. }
  29. return replacer(obj);
  30. };