I've been working on creating an Apps Script and have run into a challenge with implementing a Default Dictionary. Initially, I tried using the following code snippet:
class DefaultDict {
constructor(defaultInit) {
return new Proxy({}, {
get: (target, name) => name in target ?
target[name] :
(target[name] = typeof defaultInit === 'function' ?
new defaultInit().valueOf() :
defaultInit)
})
}
}
While this approach worked for creating a flat Default Dictionary using
let locationDict = new DefaultDict(Array)
, or new DefaultDict(Number)
, it failed when used with nested instances like new DefaultDict(DefaultDict(Array))
.
The error encountered was
TypeError: Class constructor DefaultDict cannot be invoked without 'new'
, which was puzzling as I assumed the use of the new
keyword within the class constructor would handle constructor invocations.
To resolve this issue, I transformed the class into a function:
function DefaultDict (defaultInit) {
const handler = {
get: (target, name) => name in target ?
target[name] :
(target[name] = typeof defaultInit === 'function' ?
new defaultInit().valueOf() :
defaultInit)
}
return new Proxy({}, handler)
}
Initially, it seemed to work fine even with nested instances, until running the code with actual data revealed discrepancies. To simplify, consider the following example:
const data = [["Welcome to El Mirage Sign", "El Mirage", "Arizona", "United States"],
["Indian Roller Bird", "Austin", "Texas", "United States"],
["Greenbrier Park Half-Court", "Austin", "Texas", "United States"],
["Pink Dinosaur Playscape", "Austin", "Texas", "United States"]]
const caption = 0
const subregion = 1
const region = 2
const country = 3
let locationDict = new DefaultDict(DefaultDict(DefaultDict(Array)))
for (let i = 0; i < data.length; i++)
{
const caption = data[i][0]
const subregion = data[i][1]
const region = data[i][2]
const country = data[i][3]
locationDict[country][region][subregion].push(caption)
}
console.log(locationDict)
The output displayed was not as expected, with some shared values among regions. The desired result should look more like this:
{
'United States':
{
Arizona:
{
'El Mirage': ["Welcome to El Mirage Sign"]
},
Texas:
{
Austin: ["Indian Roller Bird", "Greenbrier Park Half-Court", "Pink Dinosaur Playscape"]
}
}
This discrepancy has left me unsure about the next steps to take. Any assistance or guidance would be greatly appreciated. Thank you!