search.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. import * as strings from './strings.js';
  6. export function buildReplaceStringWithCasePreserved(matches, pattern) {
  7. if (matches && (matches[0] !== '')) {
  8. const containsHyphens = validateSpecificSpecialCharacter(matches, pattern, '-');
  9. const containsUnderscores = validateSpecificSpecialCharacter(matches, pattern, '_');
  10. if (containsHyphens && !containsUnderscores) {
  11. return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, '-');
  12. }
  13. else if (!containsHyphens && containsUnderscores) {
  14. return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, '_');
  15. }
  16. if (matches[0].toUpperCase() === matches[0]) {
  17. return pattern.toUpperCase();
  18. }
  19. else if (matches[0].toLowerCase() === matches[0]) {
  20. return pattern.toLowerCase();
  21. }
  22. else if (strings.containsUppercaseCharacter(matches[0][0]) && pattern.length > 0) {
  23. return pattern[0].toUpperCase() + pattern.substr(1);
  24. }
  25. else if (matches[0][0].toUpperCase() !== matches[0][0] && pattern.length > 0) {
  26. return pattern[0].toLowerCase() + pattern.substr(1);
  27. }
  28. else {
  29. // we don't understand its pattern yet.
  30. return pattern;
  31. }
  32. }
  33. else {
  34. return pattern;
  35. }
  36. }
  37. function validateSpecificSpecialCharacter(matches, pattern, specialCharacter) {
  38. const doesContainSpecialCharacter = matches[0].indexOf(specialCharacter) !== -1 && pattern.indexOf(specialCharacter) !== -1;
  39. return doesContainSpecialCharacter && matches[0].split(specialCharacter).length === pattern.split(specialCharacter).length;
  40. }
  41. function buildReplaceStringForSpecificSpecialCharacter(matches, pattern, specialCharacter) {
  42. const splitPatternAtSpecialCharacter = pattern.split(specialCharacter);
  43. const splitMatchAtSpecialCharacter = matches[0].split(specialCharacter);
  44. let replaceString = '';
  45. splitPatternAtSpecialCharacter.forEach((splitValue, index) => {
  46. replaceString += buildReplaceStringWithCasePreserved([splitMatchAtSpecialCharacter[index]], splitValue) + specialCharacter;
  47. });
  48. return replaceString.slice(0, -1);
  49. }