by koito17 · 2y ago · 0 comments
I noticed this part in the proposal
groupBy calls callbackfn once for each element in items, in ascending order, and constructs a new Object of arrays. Each value returned by callbackfn is coerced to a property key
Does JS allow arbitrary objects as keys? I am asking because `group-by` in ClojureScript is quite flexible. e.g. you can find anagrams like so (def words ["meat" "mat" "team" "mate" "eat" "tea"])
(group-by set words) ; set is a function that creates sets from collections
;; => {#{\a \e \m \t} ["meat" "team" "mate"]
;; #{\a \m \t} ["mat"]
;; #{\a \e \t} ["eat" "tea"]}
I am wondering how one could translate this using Object.groupBy as specified in the proposal.The symbol primitive is also allowed as an object key, using square bracket access.
And arrays are "exotic objects" that have some special behaviors around their keys (auto-updating length property)
objects = {}
items1 = ["a", "b"]
items2 = ["a", "b"]
objects[items1] = 1
objects[items2] = 2
then objects[items1] will return 1, and objects[items2] will return 2, but objects[items1] !== objects[items2].EDIT: Sorry, this only works for dictionaries that are Maps, not Objects! See the responses. My fuzzing about in the console led me astray; you should start with `objects = new Map()` instead of `objects = {}`.
> o = { [{}]: 1 }
{ '[object Object]': 1 }
> k = { toString() { return 'a' } }
{ toString: [Function: toString] }
> o = { [k]: 1 }
{ a: 1 } new Proxy(
{},
{
get(target, property) {
return typeof property
},
},
)[{}] === 'string'With a map it works like you described:
objects = new Map()
items1 = ["a", "b"]
items2 = ["a", "b"]
objects.set(items1, 1)
objects.set(items2, 2)Thanks for taking the time to explain, everybody
I've wanted to learn Clojure for years but haven't found the right reason, until discovering Logseq. Such a cool language!
Object doesn't, but Map does. It's generally a good idea to use Map anyway for dynamic keys.