utils.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* eslint-disable no-magic-numbers */
  2. "use strict";
  3. const fsAsync = require("fs").promises;
  4. const fs = require("fs");
  5. const path = require("path");
  6. /**
  7. * Check for intersection two arrays
  8. * @param {Array} arr1 array to
  9. * @param {Array} arr2 second array to combare against
  10. * @returns {boolean} is intersecting
  11. */
  12. exports.arraysHasIntersect = (arr1, arr2) => {
  13. let data = Array.isArray(arr1) ? arr1 : [arr1];
  14. for (const item of data)
  15. if (arr2.indexOf(item) != -1) return true;
  16. return false;
  17. };
  18. exports.arraysIntersect = (arr1, arr2) => {
  19. let output = [];
  20. for (const item of arr1)
  21. if (arr2.indexOf(item) != -1) output.push(item);
  22. return output;
  23. };
  24. /**
  25. * Check for intersection of array values against string
  26. * @param {string} string string to be checked for intersection
  27. * @param {string} arr1 values to check
  28. * @returns {boolean} is intersecting
  29. */
  30. exports.stringHasIntersect = (string, arr) => {
  31. arr.forEach(item => {
  32. if(string.indexOf(item) !== -1) return true;
  33. });
  34. return false;
  35. };
  36. /**
  37. * Load JSON file in async style
  38. * @param {string} path path to file
  39. * @param {string} encoding file encoding
  40. * @returns {Object|false} return false if failed or Object if successful
  41. */
  42. exports.loadJsonAsync = async (path, encoding = "utf8") => {
  43. let result = false;
  44. try {
  45. result = await fsAsync.readFile(path, encoding);
  46. }
  47. // eslint-disable-next-line no-empty
  48. catch (ex) { }
  49. if (result) result = JSON.parse(result);
  50. return result;
  51. };
  52. /**
  53. * Get full path string
  54. * @param {string} str1 resolve elem 1
  55. * @param {string} str2 relative path
  56. * @returns {string} full path
  57. */
  58. exports.getFullPath = (str1, str2) => path.resolve(str1, str2);
  59. /**
  60. * Load JSON file iin sync way
  61. * @param {string} path path to file
  62. * @param {string} encoding file encoding
  63. * @returns {Object|false} return false if failed or Object if successful
  64. */
  65. exports.loadJson = (path, encoding = "utf8") => {
  66. try {
  67. return JSON.parse(fs.readFileSync(path, encoding));
  68. } catch (err) {
  69. return false;
  70. }
  71. };
  72. /**
  73. * Save JSON file synchronously with format
  74. * @param {string} obj object to save
  75. * @param {string} path path
  76. * @returns {undefined|false} returns false if error happened
  77. */
  78. exports.saveJson = (obj, path) => {
  79. try {
  80. fs.writeFileSync(path, JSON.stringify(obj, null, "\t"));
  81. } catch (err) {
  82. return false;
  83. }
  84. };