扩展 JavaScript 中 Map 类的 keys() 和其他生成器方法。

huangapple go评论64阅读模式
英文:

extend keys() and other generator method of Map Class in javascript

问题

I understand your request. Here is the translated content:

我需要将一个对象用作我的映射的键因此我扩展了Map类它会将传递的对象转换为字符串如下所示

class CoordMapper extends Map {
set = (k: ISquareCoordinate, v: Array<ISquareCoordinate>) => {
const stringifiedKey = JSON.stringify(k)
return super.set(stringifiedKey, v)
}

get = (k: ISquareCoordinate) =&gt; {
    const stringifiedKey = JSON.stringify(k)
    return super.get(stringifiedKey)
}

}


据我了解,keys()、values()和entries()是生成器方法,因此我可以做类似以下的操作:

  • keys() {
    const keysArr = [...super.keys()]
    for (const key of keysArr){
    yield JSON.parse(key)
    }
    }

但是这会导致我加载所有的键,我希望避免这种情况,有更好的方法吗?

编辑:
虽然Map接受对象作为键,但它只检查对象的引用。例如:

let newMap = Map()
const obj1 = {'a': 1, 'b': 2}
newMap.set(obj1, 123)
const copyObj1 = {...obj1}
console.log(newMap.get(obj1)) //返回 123
console.log(newMap.get(copyObj1)) //返回 undefined


我需要第二个`console.log`也返回123。

<details>
<summary>英文:</summary>

I need to use an object as keys for my map, therefore I extended the map class that stringifies the object passed, like so

class CoordMapper extends Map {
set = (k: ISquareCoordinate, v: Array<ISquareCoordinate>) => {
const stringifiedKey = JSON.stringify(k)
return super.set(stringifiedKey,v)
}

get = (k: ISquareCoordinate) =&gt; {
    const stringifiedKey = JSON.stringify(k)
    return super.get(stringifiedKey)
}

}


As far as I understand keys(), values() and entries() are generator methods, therefore I can do something like
  • keys() {
    const keysArr = [...super.keys()]
    for (const key of keysArr){
    yield JSON.parse(key)
    }
    }
But this causes me to load all the keys which I wish to avoid, is there a better way?

EDIT:
While Map does take in objects as keys but it only checks objects by reference. As an example

let newMap = Map()
const obj1 = {'a': 1, 'b' :2}
newMap.set(obj1, 123)
const copyObj1 = {...obj1}
console.log(newMap.get(obj1)) //returns 123
console.log(newMap.get(copyObj1)) //returns undefined

And i need the second `console.log` to return 123 aswell

</details>


# 答案1
**得分**: 1

不要回答我要翻译的问题。

以下是要翻译的内容:

"Rather than collecting all the parent values into an array, just iterate over them directly:

  • keys() {
    const parentKeyIterator = super.keys();
    for (const key of parentKeyIterator){
    yield JSON.parse(key)
    }
    }

That way, the laziness of the iterator is retained: each time `next()` is called on your extended iterator, it will call `next()` on `parentKeyIterator` once, then reach your `yield` statement, and pause."

<details>
<summary>英文:</summary>

Rather than collecting all the parent values into an array, just iterate over them directly:

  • keys() {
    const parentKeyIterator = super.keys();
    for (const key of parentKeyIterator){
    yield JSON.parse(key)
    }
    }

That way, the laziness of the iterator is retained: each time `next()` is called on your extended iterator, it will call `next()` on `parentKeyIterator` once, then reach your `yield` statement, and pause.

</details>



# 答案2
**得分**: 1

以下是您要翻译的内容:

"Just in case someone stumble here in the future, there's [a stage-3 proposal][1] which, if approved, would add syntactic sugar for iterators so that you can do something like this:

```js
class CoordMapper extends Map {
  *keys() {
    yield* super.keys().map(key => JSON.parse(key));
  }
}

Try it (this doesn't work yet):

<!-- begin snippet: js hide: true -->

<!-- language: lang-js -->

console.config({ maximize: true });

class CoordMapper extends Map {
set(k, v) {
return super.set(JSON.stringify(k), v)
}
get(k) {
return super.get(JSON.stringify(k));
}
keys() {
console.log(super.keys())
yield
super.keys().map(JSON.parse);
}
}

const c = new CoordMapper();

c.set({ foo: 'bar' }, 0);
c.set({ baz: 42 }, 1);
c.set({ qux: { lorem: 'ipsum' } }, [null, undefined]);

for (const key of c.keys()) {
console.log(key);
}

<!-- language: lang-html -->

<!-- end snippet -->

英文:

Just in case someone stumble here in the future, there's a stage-3 proposal which, if approved, would add syntactic sugar for iterators so that you can do something like this:

class CoordMapper extends Map {
  *keys() {
    yield* super.keys().map(key =&gt; JSON.parse(key));
  }
}

Try it (this doesn't work yet):

<!-- begin snippet: js hide: true -->

<!-- language: lang-js -->

console.config({ maximize: true });

class CoordMapper extends Map {
  set(k, v) {
    return super.set(JSON.stringify(k), v)
  }
  get(k) {
    return super.get(JSON.stringify(k));
  }
  *keys() {
    console.log(super.keys())
    yield* super.keys().map(JSON.parse);
  }
}

const c = new CoordMapper();

c.set({ foo: &#39;bar&#39; }, 0);
c.set({ baz: 42 }, 1);
c.set({ qux: { lorem: &#39;ipsum&#39; } }, [null, undefined]);

for (const key of c.keys()) {
  console.log(key);
}

<!-- language: lang-html -->

&lt;script src=&quot;https://gh-canon.github.io/stack-snippet-console/console.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月22日 16:16:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304233.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定