{"path": "/posts/working-with-sets-and-some-ideas/", "title": "working with Sets and some ideas · Bruno Dias", "html": "<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"description\" content=\"working with Sets and some ideas\">\n  <title>working with Sets and some ideas · Bruno Dias</title>\n  <link rel=\"canonical\" href=\"https://diasbruno.github.io/posts/working-with-sets-and-some-ideas/\" data-post-metadata>\n  <meta name=\"author\" content=\"Bruno Dias\" data-post-metadata>\n  <meta property=\"og:type\" content=\"article\" data-post-metadata>\n  <meta property=\"og:title\" content=\"working with Sets and some ideas\" data-post-metadata>\n  <meta property=\"og:url\" content=\"https://diasbruno.github.io/posts/working-with-sets-and-some-ideas/\" data-post-metadata>\n  <meta property=\"article:published_time\" content=\"2023-05-04T23:19:52Z\" data-post-metadata>\n  <meta property=\"og:image\" content=\"https://diasbruno.github.io/images/working-with-sets-and-more-ideas.png\" data-post-metadata>\n  <link rel=\"icon\" href=\"/assets/site/signature.svg\" type=\"image/svg+xml\">\n  <link rel=\"alternate\" type=\"application/atom+xml\" title=\"diasbruno\" href=\"/atom.xml\">\n  <link rel=\"alternate\" type=\"application/json\" href=\"/posts/working-with-sets-and-some-ideas/content.json\">\n  <link rel=\"stylesheet\" href=\"/assets/site/tokens.css\">\n  <link rel=\"stylesheet\" href=\"/assets/site/site.css\">\n  <link rel=\"stylesheet\" href=\"/assets/site/footer.css\">\n\n</head>\n<body class=\"light\">\n<div id=\"site-page\">\n<a class=\"skip-link\" href=\"#content\">Skip to content</a>\n<header class=\"site-header\">\n  <a class=\"brand\" href=\"/\" data-site-navigation aria-label=\"Bruno Dias, home\">\n    <img src=\"/assets/site/signature.svg\" width=\"24\" height=\"34\" alt=\"\">\n  </a>\n  <nav aria-label=\"Main navigation\">\n    <ul>\n<li><a class=\"nav-vrn\" href=\"/vrn/\" data-site-navigation><span class=\"nav-label\">vrn</span> <span class=\"nav-badge\">research</span></a></li>\n<li><a class=\"nav-posts\" href=\"/posts/\" data-site-navigation aria-current=\"location\">Posts</a></li>\n<li><a class=\"nav-projects\" href=\"/projects/\" data-site-navigation>Projects</a></li>\n<li><a class=\"nav-about\" href=\"/about/\" data-site-navigation>About</a></li>\n</ul>\n  </nav>\n</header>\n\n<main class=\"section\" id=\"content\" tabindex=\"-1\">\n  <article class=\"post-detail\">\n    <header class=\"section-header\">\n      <p class=\"post-category\">Post</p>\n      <h1>working with Sets and some ideas</h1>\n\n      <p><time datetime=\"2023-05-04T23:19:52Z\">2023-05-04</time></p>\n    </header>\n    <div class=\"post-columns\">\n      <section class=\"post-body\" aria-label=\"Article\">\n\n<h2>Set interface</h2>\n<p>my conclusion is that Set is just a base class.</p>\n<p>the operations available are: <code>has</code>, <code>add</code> and <code>delete</code>.</p>\n<p>there is no <code>map</code>, or <code>filter</code>, or <code>reduce</code>.\nbut this one is kinda easy to fix...</p>\n<pre><code class=\"language-js\">class AsSet extends Set {\n  constructor(initial) {\n\tsuper(initial);\n  }\n\n  reduce(f, acc) {\n\tfor (let [_, value] of this.entries()) {\n\t  acc = f(acc, value);\n\t}\n\treturn acc;\n  }\n\n  map(f) {\n\treturn this.reduce(\n\t  (acc, item) =&gt; (acc.add(f(item)), acc),\n\t  new this.constructor()\n\t);\n  }\n\n  find(f) {\n\treturn this.reduce((acc, item) =&gt; (acc ? acc : f(item) &amp;&amp; item), null);\n  }\n}\n</code></pre>\n<p>now we have something to work on.</p>\n<p><a href=\"https://codesandbox.io/p/sandbox/quizzical-haze-qfyxow?file=%2Findex.js\">codesandbox with example</a></p>\n<p>we could implement iterator, but this one is for the reader.</p>\n<h2>the json problem</h2>\n<p>this is actually something good to talk about.</p>\n<p>json doesn't have any representation for Sets,\nonly for array.</p>\n<p>this is a serializer/deserializer problem and not a JSON one.</p>\n<p>this means that if we want to retrieve a Set from a json (and to json),\nwe need to explicitly tell that a particular value is a Set.</p>\n<p>this is great because we can parse directly into a class,\nand not use raw objects.</p>\n<pre><code class=\"language-js\">class User {\n  permissions = new Set();\n}\n\nUser.propertyToJSON = (key, value, self) =&gt; {\n  return key === &quot;permissions&quot; ? Array.from(value) : value;\n};\n\nUser.reviverJSON = (key, value) =&gt; {\n  return key === &quot;permissions&quot; ? new Set(value) : value;\n};\n\nUser.toJSON = (user) =&gt; {\n  return JSON.stringify(user, User.propertyToJSON);\n};\n\nUser.fromJSON = (json) =&gt; {\n  const { permissions } = JSON.parse(json, User.reviverJSON);\n  const user = new User();\n  user.permissions = permissions;\n  return user;\n};\n\nconst user = new User();\nuser.permissions.add(1);\n\ndeepEqual(user, User.fromJSON(User.toJSON(user)));\n</code></pre>\n<p>which means that <code>User.fromJSON . User.toJSON = id</code>.\n(it reads fromJSON composed with toJSON\nis the same of doing nothing).</p>\n<p><a href=\"https://codesandbox.io/p/sandbox/weird-ideas-with-sets-forked-5mgurt?file=%2Findex.js\">codesandbox with example</a></p>\n<p>this is handmade, but probably there is some packages smart enouth\nto help with this.</p>\n<h2>use Set when you need a Set...</h2>\n<p>this is a snippet people share on social media:</p>\n<pre><code class=\"language-js\">[...new Set(list)]\n</code></pre>\n<p>the idea is to remove duplicates from a list.</p>\n<p>let's understand what is going on.</p>\n<ul>\n<li>create a initial list</li>\n</ul>\n<p>this is ok. <code>Set</code> can be initiated with a list or another <code>Set</code>\n(like a copy constructor).</p>\n<ul>\n<li>Set will remove duplicates</li>\n</ul>\n<p>it is its job...keep only unique items.</p>\n<ul>\n<li>expand the set into a new list (?)</li>\n</ul>\n<p>this operation allocates at least a new list with size <code>N - m</code>\nbeen <code>N</code> the size of the initial list and <code>m</code> the number of duplicated\nitems. worst case is when <code>m = 0</code> meaning where are just cloning the list.</p>\n<p>the operation itself is not critical if executed once or twice,\nthe problems starts when the list grows or executing this operation\ntoo many times.</p>\n<p>the question here is why?</p>\n<p>in most cases, this operation is uneccessary. we don't really need\nto change data structures. we can just start directly with a Set\nand keep adding stuff to it.</p>\n<pre><code class=\"language-js\">let x = new Set();\nx.add(1);\nx.add(1);\nx.add(2);\n// Set { 1, 2 }\n</code></pre>\n<p>i would guess the reason is because most people use raw objects\non their projects and Set is not easily converted to/from JSON.\nmaybe it is related to what tools are available to facilitate\nserialize/deserialize objects.</p>\n<p>but there are more interesting uses of Set!</p>\n<h3>Togglable set</h3>\n<p>a nice class to work when you need to use bulk (mass) selection.</p>\n<pre><code class=\"language-js\">const ADD = &quot;add&quot;;\nconst DELETE = &quot;delete&quot;;\n\nclass Togglable extends AsSet {\n  toggle(x) {\n\tthis[this.has(x) ? DELETE : ADD](x);\n  }\n}\n\nconst a = new Togglable()\na.toggle(1);\n// Set { 1 }\na.toggle(1)\n// Set { }\na.toggle(2)\n// Set { 2 }\nArray.from(a);\n// [ 2 ]\n</code></pre>\n<p><a href=\"https://codesandbox.io/p/sandbox/togglable-set-p0vbf1?file=%2Findex.js\">codesandbox with example</a></p>\n<h3>SetWith - Set, but by a specific property of an object</h3>\n<p>Set can accept objects, but to check if the object is present\nit uses strict equality, so it must be the same instance.</p>\n<p>sometimes we don't want this. we want that it behaves live a Set\non a particular property, because we know that all objects are the same\n(they are just duplicated), or, if we try to add an item with the same key\nwe are not going to accept it (like unique constrait).</p>\n<pre><code class=\"language-js\">class SetWith extends Set {\n  constructor(initial, testFunction) {\n\tsuper();\n\tthis.sublist = {};\n\tthis.testFunction = testFunction;\n\tthis._add = this.add;\n\tthis._delete = this.delete;\n\n\tthis.add = (x) =&gt; {\n\t  const value = this.testFunction(x);\n\t  if (!this.has(value)) {\n\t\tthis.sublist[value] = x;\n\t\tthis._add(value);\n\t  }\n\t};\n\n\tthis.delete = (x) =&gt; {\n\t  const value = this.testFunction(x);\n\t  if (this.has(value)) {\n\t\tdelete this.sublist[value];\n\t\tthis._delete(value);\n\t  }\n\t};\n\n\tinitial.forEach((item) =&gt; this.add(item));\n  }\n\n  find(f) {\n\tfor (let x of Object.values(this.sublist)) {\n\t  if (f(x)) return x;\n\t}\n\treturn null;\n  }\n}\n\nconst a = new SetWith([], item =&gt; item.id);\n\na.add({ id: 1 });\n// Set() { 1, sublist: { 1: { id: 1 } } }\n\na.add({ id: 1 });\n// Set() { 1, sublist: { 1: { id: 1 } } }\n\na.add({ id: 2 });\n// Set() { 1, 2, sublist: { 1: { id: 1 }, 2: { id: 2 } } }\n</code></pre>\n<p><a href=\"https://codesandbox.io/p/sandbox/setwith-a-set-but-by-an-object-property-3cp1wv?file=%2Findex.js\">codesandbox with example</a></p>\n<p>it makes it clear what we want to accomplish. you can use this\nwhen people manually add items to a system and it shouldn't have\nduplicated values.</p>\n<pre><code class=\"language-js\">const a = new SetWith([], item =&gt; item.currency);\n\na.add({ currency: &quot;JPY&quot;, value: 2 });\na.add({ currency: &quot;USD&quot;, value: 1 });\na.add({ currency: &quot;BRL&quot;, value: 0.2 }); // :(\n\n// this next operation is impossible\n// in order to change the value you need\n// to get the reference from the set and update,\n// or delete the current one.\na.add({ currency: &quot;USD&quot;, value: 5 });\n\nconst currency = a.find(i =&gt; i.currency == &quot;USD&quot;);\ncurrency.value = 5;\n\n// now, this is feature safe by construction.\n</code></pre>\n\n      </section>\n      <aside class=\"post-links\" aria-labelledby=\"post-links-heading\">\n        <h2 id=\"post-links-heading\">Links</h2>\n        <ul>\n<li><a href=\"/posts/\" data-site-navigation>All posts</a></li>\n        </ul>\n      </aside>\n    </div>\n  </article>\n</main>\n\n<footer class=\"site-footer\">\n  <div class=\"site-footer-inner\">\n    <a class=\"site-footer-home\" href=\"/\" data-site-navigation>Bruno Dias</a>\n    <ul aria-label=\"Footer links\">\n      <li><a href=\"https://github.com/diasbruno\">GitHub</a></li>\n      <li><a href=\"/atom.xml\">Atom feed</a></li>\n    </ul>\n  </div>\n</footer>\n\n</div>\n<script type=\"module\" src=\"/assets/site/navigation.js\"></script>\n</body>\n</html>\n"}
