Skip to content

Instantly share code, notes, and snippets.

@Qs-F
Created August 30, 2020 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Qs-F/43752c9249473d935c03d603dcd5e8a2 to your computer and use it in GitHub Desktop.
Save Qs-F/43752c9249473d935c03d603dcd5e8a2 to your computer and use it in GitHub Desktop.
JS Playground - MapのKeyとしてtupleを使うには / Use tuple as Map key

背景 / Background

https://twitter.com/CreatorQsF/status/1300135251516092416

http://var.blog.jp/archives/75246136.html

考えと実装 / Idea and Implementation

普通に JSON.stringify を使って、 tuple に限らず Objectstring にしてkeyに設定する

Use JSON.stringify so that key will be string of not only tuple but Object

const f = (key: any): string => {
  return JSON.stringify(key);
};

const m = new Map();
const k1 = [1, "hello"];
const v1 = "hello world";
const k2 = [2, "world"];
const v2 = "tuple map";
const k3 = [1, "hello"];

m.set(f(k1), v1);
m.set(f(k2), v2);
if (m.get(f(k3)) === v1) console.log("ok");
else console.error("not same");

// output: ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment