optimize.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. /**
  3. * optimize try catch
  4. * @param {Function} fn
  5. * @return {Object}
  6. * - {Error} error
  7. * - {Mix} value
  8. */
  9. exports.try = function (fn) {
  10. var res = {
  11. error: undefined,
  12. value: undefined
  13. };
  14. try {
  15. res.value = fn();
  16. } catch (err) {
  17. res.error = err instanceof Error
  18. ? err
  19. : new Error(err);
  20. }
  21. return res;
  22. };
  23. /**
  24. * @description Deal with typescript
  25. */
  26. exports.UNSTABLE_METHOD = {
  27. try: exports.try,
  28. };
  29. /**
  30. * avoid if (a && a.b && a.b.c)
  31. * @param {Object} obj
  32. * @param {...String} keys
  33. * @return {Object}
  34. */
  35. exports.dig = function (obj) {
  36. if (!obj) {
  37. return;
  38. }
  39. if (arguments.length <= 1) {
  40. return obj;
  41. }
  42. var value = obj[arguments[1]];
  43. for (var i = 2; i < arguments.length; i++) {
  44. if (!value) {
  45. break;
  46. }
  47. value = value[arguments[i]];
  48. }
  49. return value;
  50. };
  51. /**
  52. * optimize arguments to array
  53. * @param {Arguments} args
  54. * @return {Array}
  55. */
  56. exports.argumentsToArray = function (args) {
  57. var res = new Array(args.length);
  58. for (var i = 0; i < args.length; i++) {
  59. res[i] = args[i];
  60. }
  61. return res;
  62. };