interpolation.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.getPath = getPath;
  6. exports.interpolateVariables = void 0;
  7. function _jestGetType() {
  8. const data = require('jest-get-type');
  9. _jestGetType = function () {
  10. return data;
  11. };
  12. return data;
  13. }
  14. function _prettyFormat() {
  15. const data = require('pretty-format');
  16. _prettyFormat = function () {
  17. return data;
  18. };
  19. return data;
  20. }
  21. /**
  22. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  23. *
  24. * This source code is licensed under the MIT license found in the
  25. * LICENSE file in the root directory of this source tree.
  26. *
  27. */
  28. const interpolateVariables = (title, template, index) =>
  29. Object.keys(template)
  30. .reduce(getMatchingKeyPaths(title), []) // aka flatMap
  31. .reduce(replaceKeyPathWithValue(template), title)
  32. .replace('$#', '' + index);
  33. exports.interpolateVariables = interpolateVariables;
  34. const getMatchingKeyPaths = title => (matches, key) =>
  35. matches.concat(title.match(new RegExp(`\\$${key}[\\.\\w]*`, 'g')) || []);
  36. const replaceKeyPathWithValue = template => (title, match) => {
  37. const keyPath = match.replace('$', '').split('.');
  38. const value = getPath(template, keyPath);
  39. if ((0, _jestGetType().isPrimitive)(value)) {
  40. return title.replace(match, String(value));
  41. }
  42. return title.replace(
  43. match,
  44. (0, _prettyFormat().format)(value, {
  45. maxDepth: 1,
  46. min: true
  47. })
  48. );
  49. };
  50. /* eslint import/export: 0*/
  51. function getPath(template, [head, ...tail]) {
  52. if (!head || !template.hasOwnProperty || !template.hasOwnProperty(head))
  53. return template;
  54. return getPath(template[head], tail);
  55. }