0

I've written some code that uses ECMAScript 6 Sets in various recursive functions, to keep track of objects that have already been encountered (thereby avoiding infinite recursion); e.g.

function traverse(start, callback, next) {
    var seen = new Set();
    function _traverse(obj) {
        if (seen.has(obj)) { return }
        seen.add(obj);
        callback(obj);
        _traverse(next(obj));
    }
    return _traverse(start);
}

I prefer to use these Sets for this purpose over plain Objects, because the former distinguish between, e.g., between the integer 0 and the string "0".

It is my understanding, however, that browser support for such Sets may not yet be widespread enough for production code. Therefore, I'm looking for a more portable replacement with equal functionality (such as, e.g., distinguishing 0 and "0", as described above).

4

1 回答 1

1

在我的脑海中,这可以通过一个对象和一些代码来完成。

一个对象是一个hash,因此可以为您提供 80% 的所需功能。js 对象的问题是它们的键总是字符串。这是您编写一些代码的地方。

我会创建 2 个对象:

一种是您的键是字符串,另一种是您的键以数字开头但变成字符串。如果您要插入的东西是数字,请签入数字对象,如果是字符串,请签入另一个对象。

伪代码:

numObj = {}
strObj = {}

add = (val) ->
  if _.isNumber(val)
    numObj[val] = true
  else
    strObj[val] = true

contains = (val) ->
  if _.isNumber(val)
    return !!numObj[val]
  else
    return !!strObj[val]
于 2013-09-05T02:19:12.783 回答