Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extend map operator in rxjs?

I want to create a new operator like map. but the different is whatever map returns I need to clone it using JSON.parse(JSON.stringify(value)).

Because I return an object from my store (Subject), and I don’t want somebody to change it, or it’s inner properties.

I copy the map singture to my mapToVM function, but I can’t find any way to use pipe or manipulate the return results.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is it possible to change the return results by wrapping the map operator?

codesandbox

So I try to return the map function and take the source as Observable, but typescript

import { map, Observable, OperatorFunction, Subject } from "rxjs";

console.clear();

const store = new Subject<{ company: { id: number } }>();

store.pipe(map((s) => s.company)).subscribe((company) => {
  console.log({ company });
});

function mapToVM<T, R>(
  project: (value: T, index: number) => R
): OperatorFunction<T, R> {
  // JSON.parse(JSON.stringify(source));
  return map(project);
}

store.pipe(mapToVM((s) => s.company)).subscribe((company) => {
  console.log({ company });
});

store.next({ company: { id: 1 } });

>Solution :

you can use the static pipe function:

function jsonClone<T>(): OperatorFunction<T, T> {
  return pipe(map((source) => JSON.parse(JSON.stringify(source))));
}

Full CodeSandbox example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading