JsCoder
JsCoder

Reputation: 1733

How to create a collection of items referencing collection itself

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

Upvotes: 1

Views: 57

Answers (2)

Bergi
Bergi

Reputation: 665090

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; }}));

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138457

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);

Upvotes: 0

Related Questions