I
I
Irina2022-04-09 17:52:53
JavaScript
Irina, 2022-04-09 17:52:53

How can I optimize (improve) the code?

There is this code:

const data = []

import data1 from './data1'
import data2 from './data2'
import data3 from './data3'
import data4 from './data4'
import data5 from './data5'
import data6 from './data6'
import data7 from './data7'
import data8 from './data8'
import data9 from './data9'

data.push(data1)
data.push(data2)
data.push(data3)
data.push(data4)
data.push(data5)
data.push(data6)
data.push(data7)
data.push(data8)
data.push(data9)

export default data

further, the number of imported files of the type dataN will increase. I would like to somehow change the code to simply indicate the number of files like const len ​​= 9; and that the entire list is imported. I tried to do import through a cycle - but it doesn’t work like that, import after from does not accept a variable ... Maybe someone will suggest an idea?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2022-04-09
@irikonova45

Of course, you can try this way, but isn't it easier to change the structure of such files?

const count = 2;

export default await Promise.all(
    Array.from({ length: count }, async (_, index) => (await import(`./data${index + 1}.js`)).default)
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question