Reputation: 3825
How to simplify this code?
I want the method to return instances of TorrentFile
getFiles(id: string): Observable<TorrentFile[]> {
return this.http
.get<ITorrentFile[]>(
`${ this.resourceUrl }/${ id }/files`,
)
.pipe(map(
(items: ITorrentFile[]) => {
const data: UserTorrent[] = [];
for (let i = 0; i < items.length; i++) {
items[ i ] = new TorrentFile(items[ i ]);
}
return items;
})
);
}
The TorrentFile
class ans interface looks like this:
export interface ITorrentFile {
name: string;
length: number;
bytesCompleted: number;
}
export class TorrentFile implements ITorrentFile {
public name = '';
public length = 0;
public bytesCompleted = 0;
constructor(object: ITorrentFile) {
return Object.assign(this, object);
}
}
Upvotes: 0
Views: 1027
Reputation: 691765
Arrays have a map() method, too:
.pipe(map(items => items.map(item => new TorrentFile(item))));
Upvotes: 1
Reputation: 11934
I don't think there is much you can simplify, but here's what comes to mind:
getFiles(id: string): Observable<TorrentFile[]> {
return this.http
.get<ITorrentFile[]>(
`${ this.resourceUrl }/${ id }/files`,
)
.pipe(map(
(items: ITorrentFile[]) => items.map(item => new TorrentFile(item)))
);
}
Upvotes: 1
Reputation: 11345
Your code is already quite clean, I'll only simplify the looping with map
getFiles(id: string): Observable<TorrentFile[]> {
return this.http
.get<ITorrentFile[]>(
`${ this.resourceUrl }/${ id }/files`,
)
.pipe(map((items: ITorrentFile[]) =>items.map(item=>new TorrentFile(item)))
);
}
Upvotes: 1