Given the requirement to create a nested array or arbitrary depth, where the basic data structure is
[0, [1, [2, [3 /* , [N, [N+1, [..]]] */]]]]
or
["a", ["b", ["c", ["d" /* , [N, [N+1, [..]]] */]]]]
where arr is an Array instance and and map an Map instance the requirement is to map each depth is mapped to a Map object, where
map.get(2) // 2
or
map.get(2) // "c"
gets the value set at the nested array at index N where N are the linear indexes of the nested array.
In additions, the requirement is to have the ability to execute
m.set(2, "x")
which will result in
["a", ["b", ["x", ["d" /* , [N, [N+1, [..]]] */]]]]
Have been able to create the nested array data structure using Array.prototype.map() and two additional Array.
Am probably missing a simply adjustment which can be made to achieve the expected functionality. The current code only performs the m.get(<index>) procedure.
const treeMap = (tree, props = (!Array.isArray(tree) && typeof tree === "string"
? tree.split` `
: tree), res = [], t = [], m = new Map) => props.map((prop, index) =>
!res.length // first iteration
? res.push(prop, t) && m.set(index, prop) // push first value
: index < props.length-1 // check index
? t.push(prop, t = []) && m.set(index, prop) // `.push()` to `t`, re-declare `t` as `[]`
: t.push(prop) && m.set(index, t[0])) // `.push()` last value `prop` to `t`
&& [res, m] // return `res`
let [arr, map] = treeMap("a b c");
console.log(arr, map);
console.log(map.get(2));
// console.log(treeMap([...Array(3).keys()]));
// [0, [1, [2, [3]]]]
After only two attempts decided to ask for a solution here, instead of simply solving the inquiry for self first. In general, test code several if not hundreds or thousands of times over, before asking a question.
How to achieve the above described requirement?
.setis meant to, essentially, set a property of the current map instance. Calling.seton a Map should only set the property of that Map, and shouldn't (and can't) mutate an external object, at least in sane code, unless you overwriteMap.prototype.set, which is really weird. Is themapvariable required to be an actualMap, or can you return an object which simulates aMapwhile achieving the other requirements?Mapis not restricted. Would initially probably avoid using aProxyto limit the amount of objects needed to achieve the requirement, though using aProxyis not explicitly restricted in the question. The main requirement is being able to set the nth nested array index in linear order by considering the nested array data structure as only a an array of linear indexes0-n