返回镜像数组的函数,其中空元素在另一个数组中标记空格/变音符号

问题描述 投票:0回答:0

我正在尝试创建一个函数,在其中我们传递两个参数:leftPalindrome和rightPalindrome(这是两个可以读取为彼此的反转的文本。在这个示例中,我们传递两个字符串:“bard'sloop”和“池单调”-它们有相反的字母,但不是字符)。

该函数需要返回一个带有数组的对象,其中包含上述两个参数,但以这样的方式进行分割:等价的字母始终位于文本中相同(但相反)的位置,而所有其他非字母字符(例如空格、撇号、点、逗号等)仅在一个数组中,而在另一个数组中,在等效位置,是一个空元素,实际上表示“在另一个文本中的这个位置,有一个虚拟字符”。我在下面定义了这些字符:

const dummyCharacters = /[.,\/#!$%^&*;:{}=\-_~()
<>'"[]@+?\s]/g;`

除此之外,这种形式还提供了字母的变体:

const diacriticVariations = { a: ['a', 'à', 'á', 'â', 'ä', 'å', 'ã', 'æ', 'ā', 'ă', 'ą'] }

所以:如果我们将“吟游诗人循环”传递到左回文参数中,并将“池单调”传递到右回文参数中,我们应该得到一个由两个数组组成的数组:

[“b”,“a”,“r”,“d”,“”,“'”,“s”,“”,“l”,“o”,“o”,“p”] [“p”,“o”,“o”,“l”,“s”,“”,“”,“d”,“r”,“a”,“b”,]

注意“ ”(空格)和“”(空元素)之间的区别。

这是我能够编写的函数:

function ConstructsPalindromeBlueprint(palindromeLeft, palindromeRight) {
  let constructorArrayFromLeftPalindrome = [];
  let constructorArrayFromRightPalindrome = [];
  let newLeft = palindromeLeft.split('');
  let newRight = palindromeRight.split('').reverse();

  while (newLeft.length > 0 || newRight.length > 0) {
    const leftLastChar = newLeft[newLeft.length - 1];
    const rightLastChar = newRight[newRight.length - 1];

    if (leftLastChar === rightLastChar || leftLastChar.toLowerCase() === rightLastChar.toLowerCase()) {
      constructorArrayFromLeftPalindrome.push(newLeft.pop());
      constructorArrayFromRightPalindrome.push(newRight.pop());
      newLeft.pop();
      newRight.pop();
    } else if (
      diacriticVariations[leftLastChar.toLowerCase()] &&
      diacriticVariations[leftLastChar.toLowerCase()].includes(rightLastChar.toLowerCase())
    ) {
      constructorArrayFromLeftPalindrome.push(newLeft.pop());
      constructorArrayFromRightPalindrome.push(newRight.pop());
      newLeft.pop();
      newRight.pop();
    } else if (dummyCharacters.test(leftLastChar)) {
      constructorArrayFromLeftPalindrome.push(newLeft.pop());
      constructorArrayFromRightPalindrome.push('');
      newLeft.pop();
    } else if (dummyCharacters.test(rightLastChar)) {
      constructorArrayFromLeftPalindrome.push('');
      constructorArrayFromRightPalindrome.push(newRight.pop());
      newRight.pop();
    } else {
      break;
    }
  }

  const returnedPalindromeBlueprint = [
    constructorArrayFromLeftPalindrome,
    constructorArrayFromRightPalindrome.reverse(),
  ];

  return returnedPalindromeBlueprint;
}

但是当我尝试console.log它时,它没有给出预期的效果。事实上,我不明白数据流中究竟发生了什么。

console.log(ConstructsPalindromeBlueprint("bard's loop", "pools drab"));

我花了一整天的时间研究这个功能,我发现它很难修复。如果有人好心帮助我,我会非常高兴。

javascript function iteration palindrome mirroring
© www.soinside.com 2019 - 2024. All rights reserved.