template.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.getPath = getPath;
  6. exports.default = void 0;
  7. function _prettyFormat() {
  8. const data = _interopRequireDefault(require('pretty-format'));
  9. _prettyFormat = function _prettyFormat() {
  10. return data;
  11. };
  12. return data;
  13. }
  14. function _jestGetType() {
  15. const data = require('jest-get-type');
  16. _jestGetType = function _jestGetType() {
  17. return data;
  18. };
  19. return data;
  20. }
  21. function _interopRequireDefault(obj) {
  22. return obj && obj.__esModule ? obj : {default: obj};
  23. }
  24. /**
  25. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  26. *
  27. * This source code is licensed under the MIT license found in the
  28. * LICENSE file in the root directory of this source tree.
  29. *
  30. */
  31. var _default = (title, headings, row) => {
  32. const table = convertRowToTable(row, headings);
  33. const templates = convertTableToTemplates(table, headings);
  34. return templates.map(template => ({
  35. arguments: [template],
  36. title: interpolate(title, template)
  37. }));
  38. };
  39. exports.default = _default;
  40. const convertRowToTable = (row, headings) =>
  41. Array.from({
  42. length: row.length / headings.length
  43. }).map((_, index) =>
  44. row.slice(
  45. index * headings.length,
  46. index * headings.length + headings.length
  47. )
  48. );
  49. const convertTableToTemplates = (table, headings) =>
  50. table.map(row =>
  51. row.reduce(
  52. (acc, value, index) =>
  53. Object.assign(acc, {
  54. [headings[index]]: value
  55. }),
  56. {}
  57. )
  58. );
  59. const interpolate = (title, template) =>
  60. Object.keys(template)
  61. .reduce(getMatchingKeyPaths(title), []) // aka flatMap
  62. .reduce(replaceKeyPathWithValue(template), title);
  63. const getMatchingKeyPaths = title => (matches, key) =>
  64. matches.concat(title.match(new RegExp(`\\$${key}[\\.\\w]*`, 'g')) || []);
  65. const replaceKeyPathWithValue = template => (title, match) => {
  66. const keyPath = match.replace('$', '').split('.');
  67. const value = getPath(template, keyPath);
  68. if ((0, _jestGetType().isPrimitive)(value)) {
  69. return title.replace(match, String(value));
  70. }
  71. return title.replace(
  72. match,
  73. (0, _prettyFormat().default)(value, {
  74. maxDepth: 1,
  75. min: true
  76. })
  77. );
  78. };
  79. /* eslint import/export: 0*/
  80. function getPath(template, [head, ...tail]) {
  81. if (!head || !template.hasOwnProperty || !template.hasOwnProperty(head))
  82. return template;
  83. return getPath(template[head], tail);
  84. }