CorrectRoadH / CorrectRoadH.github.io

个人博客
https://correctroadh.github.io
MIT License
6 stars 1 forks source link

posts/techstack-regexp-map #4

Open utterances-bot opened 11 months ago

utterances-bot commented 11 months ago

TechStack背后的故事: 因需求诞生的特殊数据结构:正则Map

前情 TechStack 是一个用于显示一个 Github 项目的技术栈的浏览器插件。在开发它的过程中,我遇到一个挺有意思的技术需求。 比如在 package.json 中,我们可以通过依赖项 react 直接映射到 React 技术栈。但是有些依赖并不是这样。 比如 @radix-ui/react-checkbox 和 @radix-ui/react-icons 它们都属于 Radix UI 的一部分,如果让这些依赖直接对应到 Radix 呢? 我觉得大部分人都很想容易想到正则。对,可以写一个正则,大概是这样@radix-ui/

https://correctroadh.github.io/p/techstack%E8%83%8C%E5%90%8E%E7%9A%84%E6%95%85%E4%BA%8B-%E5%9B%A0%E9%9C%80%E6%B1%82%E8%AF%9E%E7%94%9F%E7%9A%84%E7%89%B9%E6%AE%8A%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E6%AD%A3%E5%88%99map/

couriourc commented 11 months ago

有趣的结构,大半夜看到,好玩,哈哈哈。然后起床顺手写了一个反向的


class MapRegExp {
  value = {};
  constructor(map) {
    this.value = new Proxy(map, {
      get(target, keys) {
        if (keys.startsWith('/') && keys.endsWith('/')) {
          const reg = new RegExp(keys.replaceAll('/', ''));
          // TODO: 优化查询能力
          return Object.keys(target).filter(key => {
            return reg.test(key);
          }).reduce((pre, now) => {
            return {
              ...pre,
              [now]: target[now]
            }
          }, {});
        };

        return target[keys]
      }
    })
  }
}
const array = new MapRegExp(new Array(10000).fill(1));
console.log(array.value['/^4\\d4$/']); // {"404":1,"414":1,"424":1,"434":1,"444":1,"454":1,"464":1,"474":1,"484":1,"494":1}