使用javascript编写CSS特异性函数

Use javascript to write CSS specificity function

我需要编写一个 javascript 函数来比较传入的两个参数。它们将是字符串。并代表 CSS classes.

该函数的目的是对 CSS 特异性进行加权。因此,如果传入的参数是一个 CSS ID,则它应该被 returned 而不是第二个参数。 (例如,如果 a = '#id',它将击败 b = '.red')。

有点迷失了 javascript 函数的最佳方法。不确定是使用 if/else 语句还是 switch/case。不管怎样,它变得越来越乱,需要一些指点。

这是我正在尝试做的事情:

我最近在一次求职面试中 运行 遇到了这个确切的问题,我是这样想出来的:

function compare(a, b) {
  let aItems = a.split([" "]);
  let aRating = [0, 0, 0];

  aItems.forEach((i) => {
    if (i.split("#").length > 1) {
      aRating[0] = aRating[0] + (i.split("#").length - 1);
    }

    if (i.split(".").length > 1) {
      aRating[1] = aRating[1] + (i.split(".").length - 1);
    }

    if (!i.startsWith("#") && !i.startsWith(".")) {
      aRating[2] = aRating[2] + 1;
    }
  });

  let bItems = b.split([" "]);
  let bRating = [0, 0, 0];

  bItems.forEach((i) => {
    if (i.split("#").length > 1) {
      bRating[0] = bRating[0] + (i.split("#").length - 1);
    }

    if (i.split(".").length > 1) {
      bRating[1] = bRating[1] + (i.split(".").length - 1);
    }

    if (!i.startsWith("#") && !i.startsWith(".")) {
      bRating[2] = bRating[2] + 1;
    }
  });

  if (aRating[0] > bRating[0]) {
    return a;
  } else if (bRating[0] > aRating[0]) {
    return b;
  }

  if (aRating[1] > bRating[1]) {
    return a;
  } else if (bRating[1] > aRating[1]) {
    return b;
  } else if (
    bRating[0] === aRating[0] &&
    bRating[2] === 0 &&
    aRating[2] === 0
  ) {
    return b;
  }

  if (aRating[2] > bRating[2]) {
    return a;
  } else if (bRating[2] > aRating[2]) {
    return b;
  }
}

虽然有一个问题,假设您正在比较 tagnames(即 htmlbody,其中越具体,特异性越高),那么您可能有一些困难。我能够破解它的 if else 测试字符串。