1

I'm looking for a way of creating a collection of items, each of which would reference the collection itself.

Given:

const sources = [1, 2, 3];

Expected:

const results = [{value:1, items:[{value: 1, items:[{value: 1, items...}, ...]}]}]

Broken due to the fact that arrays are copied by value in js code:

const source = [1, 2, 3];
let result = [];

result = source.map(value => ({ value, items: result }));

I've tried a few things mainly around (()=> ...)(), but that gave me nothing. I managed to get it working with items being a function as opposed to value, which isn't exactly what I want.

Here's the best solution I found so far:

Code:

const source = [1, 2, 3];
let items = [];

items = source.map(value => () => ({ value, items }));

Usage:

items[1]().items[1]().value // 2
items[1]().items[2]().items[0]().value // 1
JsCoder
  • 117
  • 1
  • 9

2 Answers2

1

Self-references in object literals / initializers applies here. In your case, getters would be a good solution:

const result = [1, 2, 3].map(value => ({value, get items() { return result; }}));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

That can't be done in one step. You have to create an array of objects first:

 const results = sources.map(value => ({ value }));

Then link back:

 results.forEach(result => result.items = results);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • I was thinking of using curry'ed constructors but I don't have much experience with currying - any value to be had by using it here? – JsCoder May 02 '19 at 10:01