【问题标题】:Efficient way of finding a description in a dictionary with synonyms使用同义词在字典中查找描述的有效方法
【发布时间】:2020-09-24 22:00:47
【问题描述】:

我有以下结构:

const dictionary = [
  {
    words: ["foo", "bar"],
    desc: "This is a description"
  },
  {
    words: ["some", "word"],
    desc: "This is another description"
  }
]

我想访问给定单词的desc。例如:

getDescription(dictionary, "some") // "This is another description"

getDescription 的初始实现如下所示:

function getDescription(list, word) {
  return list.find(item => item.words.includes(word)).desc
}

这是一种非常简单的方法,但我想知道是否可以将 list 转换为其他东西以提高效率(在速度方面),如果说 list 有 5000 个项目,其中 @987654329 @ 从 1 到 5 或 6 不等。

例如,这种初始转换会有帮助吗?:

list = list.reduce((acc, item) => ({
    ...acc,
    ...item.words.reduce((acc, word) => ({
      ...acc,
      [word]: item.desc
    }), {})
  }), {}
  )
}

它会重复很多描述,但访问将是即时的 (list["some"] // This is another description)。

这些问题都存在吗?我会感觉到任何性能的速度差异吗?优化,还是只是浪费时间?

【问题讨论】:

标签: javascript arrays performance optimization reduce


【解决方案1】:

dictionary 的任何预处理都会提高您的性能。将其转换为对象会将复杂度从 O(n) 降低到 O(1)。也就是说,您应该将您的字典逐字转换为Map,因为它们是为这类事情创建的。这通常是像 Elasticsearch 这样的 inverted index 的工作方式。

const dictionary = [
  {
    words: ["foo", "bar"],
    desc: "This is a description"
  },
  {
    words: ["some", "word"],
    desc: "This is another description"
  }
]

const { pipe, map, reduce } = rubico

const incrementMap = (m, [word, desc]) => {
  if (m.has(word)) {
    m.get(word).push(desc)
  } else {
    m.set(word, [desc])
  }
  return m
}

const flatten = arr => arr.flat(1)

// dictionary_arr => inverted_index
const createInvertedIndex = pipe([
  map(({ words, desc }) => map(
    word => [word, desc],
  )(words)),
  flatten,
  reduce(incrementMap, new Map()),
])

const maptionary = createInvertedIndex(dictionary)

console.log('maptionary.get(\'some\')', maptionary.get('some'))
<script src="https://unpkg.com/rubico/index.js"></script>

上面的例子使用了我的库,rubico。我建议您拨打tour 以更好地了解正在发生的事情。

【讨论】:

  • 如果我可以在没有任何外部库的情况下解决这个问题,我会更喜欢,我会检查你的示例是否是一个很好的基础。
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 2021-03-17
  • 2016-03-17
  • 2014-11-16
  • 2014-04-17
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
相关资源
最近更新 更多