Hett
Hett

Reputation: 3825

rxjs: how to replace each element of array

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

Answers (3)

JB Nizet
JB Nizet

Reputation: 691765

Arrays have a map() method, too:

    .pipe(map(items => items.map(item => new TorrentFile(item))));

Upvotes: 1

Andrei Gătej
Andrei Gătej

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

Fan Cheung
Fan Cheung

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

Related Questions