<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Denis Loh on Medium]]></title>
        <description><![CDATA[Stories by Denis Loh on Medium]]></description>
        <link>https://medium.com/@denis.loh?source=rss-aad7607062a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a_itUtN4Wvg1ijlhx0kW2Q.jpeg</url>
            <title>Stories by Denis Loh on Medium</title>
            <link>https://medium.com/@denis.loh?source=rss-aad7607062a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:31:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@denis.loh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Immutable Builder Pattern with Typescript]]></title>
            <link>https://medium.com/@denis.loh/immutable-builder-pattern-with-typescript-fe7bad33008b?source=rss-aad7607062a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe7bad33008b</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[immutable-objects]]></category>
            <dc:creator><![CDATA[Denis Loh]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 13:23:06 GMT</pubDate>
            <atom:updated>2024-10-01T06:38:15.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OUnEUVJ2XAOQFGAw" /><figcaption>Photo by <a href="https://unsplash.com/@danist07?utm_source=medium&amp;utm_medium=referral">Danist Soh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When you deal with complex objects with different representations, you will likely come also across with builder design pattern, which allows you to streamline the creation process of the object.</p><p>So what does the builder pattern do? It basically decouples the object creation from the actual object representation. Especially with complex objects, it helps to construct and assemble the parts in the right order and allows to respect dependencies between the parts. This is how <a href="https://en.wikipedia.org/wiki/Builder_pattern">Wikipedia</a> describes the builder pattern:</p><figure><a href="https://en.wikipedia.org/wiki/Builder_pattern"><img alt="In the above UML class diagram, the Director class doesn’t create and assemble the ProductA1 and ProductB1 objects directly. Instead, the Director refers to the Builder interface for building (creating and assembling) the parts of a complex object, which makes the Director independent of which concrete classes are instantiated (which representation is created). The Builder1 class implements the Builder interface by creating and assembling the ProductA1 and ProductB1 objects.
CC-BY-SA Wikipedia" src="https://cdn-images-1.medium.com/max/700/1*TZ-42ZEGvgIVKlXz001jCQ.jpeg" /></a><figcaption>Wikimedia Commons CC-BY-SA <a href="https://commons.wikimedia.org/wiki/User:Vanderjoe">Vanderjoe</a></figcaption></figure><h3>Typical typescript example</h3><p>The following example shows a very simple builder pattern implementation:</p><pre>interface Builder {<br>  setWheels(wheels: number): this<br>  setEngine(engine: string): this<br>  build(): Car<br>}<br><br>class Car {<br><br>  public wheels: number<br>  public engine: string<br><br>  constructor() {<br>    this.wheels = 0<br>    this.engine = &quot;&quot;<br>  }<br><br>}<br><br>class CarBuilder implements Builder {<br>  private car: Car<br><br>  constructor() {<br>    this.car = new Car()<br>  }<br><br>  setWheels(wheels: number): this {<br>    this.car.wheels = wheels<br>    return this<br>  }<br><br>  setEngine(engine: string): this {<br>    this.car.engine = engine<br>    return this<br>  }<br><br>  build(): Car {<br>    return this.car<br>  }<br><br>}<br><br>class CarDirector {<br><br>  constructor(private builder: Builder) {}<br><br>  constructCar() {<br>    this.builder.setWheels(4).setEngine(&quot;V8-Boxer&quot;)<br>  }<br><br>  getCar(): Car {<br>    return this.builder.build()<br>  }<br><br>}<br><br>const director = new CarDirector(new CarBuilder())<br>director.constructCar()<br>const myCar = director.getCar()</pre><p>The Builder interface defines what parts need to be defined and also how to build the concrete product. The Car class is our complex object, which we want to construct. With the CarBuilder we define how to produce a car and define its properties. The CarDirector then specifies the order of the operations and the details.</p><p>To obtain an instance of the car, you “hire” a CarDirector which uses a CarBuilder to construct the car and afterwards you can get the result from the Director.</p><h3>Instance Creation and Modification</h3><p>The example above has some flaws in it. First of all, the builder pattern adds quite a lot of additional boiler plate code, which you might wonder it is required for. Essentially, you want to achieve two things with the builder pattern:</p><ol><li>Avoid to implement the complex object creation yourself every time you need an instance of this object.</li><li>Make sure, that the object is created in the right way and does not contain contradictions.</li></ol><p>With our car example it is very easy that an instance of a car can be created without considering the rules of the objects. For example it is possible to simply create an instance without any values:</p><pre>const newCar = new Car()</pre><p>To circumvent this issue, we could put the properties into the constructor and postpone the creation of the car into the build method:</p><pre>class Car {<br><br>  constructor(<br>    public wheels: number,<br>    public engine: string<br>  ) {}<br><br>}<br><br>class CarBuilder implements Builder {<br>  private wheels!: number<br>  private engine!: string<br><br>  constructor() {<br>  }<br><br>  setWheels(wheels: number): this {<br>    this.wheels = wheels<br>    return this<br>  }<br><br>  setEngine(engine: string): this {<br>    this.engine = engine<br>    return this<br>  }<br><br>  build(): Car {<br>    return new Car(this.wheels, this.engine)<br>  }<br><br>}</pre><p>But as we still have public properties, we can modify the values to something, which might contradicts with the nature of the object:</p><pre>const director = new CarDirector(new CarBuilder())<br>director.constructCar()<br>const myCar = director.getCar()<br><br>myCar.wheels = 2 // What does that mean? Is it now a motorcycle?</pre><p>Okay, so let’s make the properties readonly then:</p><pre>class Car {<br><br>  constructor(<br>    readonly wheels: number,<br>    readonly engine: string<br>  ) {}<br><br>}<br><br>const director = new CarDirector(new CarBuilder())<br>director.constructCar()<br>const myCar = director.getCar()<br><br>myCar.wheels = 2 // Cannot assign to &#39;wheels&#39; because it is a read-only property.</pre><p>But we still haven’t solved the major problem, that you can create instances of a car without the builder pattern involved:</p><pre>const myOwnCar = new Car(6, &quot;My Own Engine&quot;)</pre><p>With that, we would have to maintain all the business logic of the instance creation in the constructor of the object. As the builder pattern is especially useful for very complex objects, it is very likely, that you do not have only one or two parameters, but dozens or more, where some of them are optional and others have dependencies and so on. So, when you introduce a builder pattern, you want to simplify this and extract that to a dedicated class.</p><h3>Private Constructor with readonly properties</h3><p>The ideal object should be immutable, which means that all properties (including child properties) are readonly once the instance has been created and it cannot be created from public space.</p><pre>class Car {<br><br>  private constructor(<br>    readonly wheels: number,<br>    readonly engine: string<br>  ) {}<br><br>}</pre><p>However, typescript does not support concepts like package private classes or nested classes. This means, that our CarBuilder fails:</p><pre>class CarBuilder implements Builder {<br>  private wheels!: number<br>  private engine!: string<br><br>  ...<br><br>  build(): Car {<br>    return new Car(this.wheels, this.engine) // Constructor of class &#39;Car&#39; is private and only accessible within the class declaration.<br>  }<br><br>}</pre><h3>Constructor Callback</h3><p>The only way to create an instance of a class with a private constructor is from within the class itself. So, we can do something like this:</p><pre>class Car {<br><br>  private constructor(<br>    readonly wheels: number,<br>    readonly engine: string<br>  ) {}<br><br>  static createCar(wheels: number, engine: string) : Car {<br>    return new Car(wheels, engine)<br>  }<br><br>}</pre><p>If we now want to involve our builder in that process, we have to let the car create the builder with an instance creator for us:</p><pre>class Car {<br><br>  private constructor(<br>    readonly wheels: number,<br>    readonly engine: string<br>  ) {}<br><br>  static builder() : CarBuilder {<br>    return new CarBuilder((wheels, engine) =&gt; new Car(wheels, engine))<br>  }<br><br>}<br><br>class CarBuilder implements Builder {<br>  private wheels!: number<br>  private engine!: string<br><br>  constructor(private builder: (wheels: number, engine: string) =&gt; Car) {<br>  }<br><br>  setWheels(wheels: number): this {<br>    this.wheels = wheels<br>    return this<br>  }<br><br>  setEngine(engine: string): this {<br>    this.engine = engine<br>    return this<br>  }<br><br>  build(): Car {<br>    return this.builder(this.wheels, this.engine)<br>  }<br><br>}</pre><p>Now it is not possible anymore to create an instance of a car without the builder involved and you are restricted to read its properties only.</p><pre>const director = new CarDirector(Car.builder())<br>director.constructCar()<br>const myCar = director.getCar()<br><br>myCar.wheels = 2 // Fails<br>const myOwnCar = new Car(6, &quot;My Own Engine&quot;) // Fails</pre><h3>Add-on</h3><p>You can even more simplify the resulting pattern with the spread-operator (…) by providing a type-tuple to the constructor:</p><pre>class Car {<br><br>  private constructor(<br>    readonly wheels: number,<br>    readonly engine: string<br>  ) {}<br><br>  static builder() : CarBuilder {<br>    return new CarBuilder((...args) =&gt; new Car(...args))<br>  }<br><br>}<br><br>class CarBuilder implements Builder {<br>  private wheels!: number<br>  private engine!: string<br><br>  constructor(private builder: (...args: [number, string]) =&gt; Car) {<br>  }<br><br>  setWheels(wheels: number): this {<br>    this.wheels = wheels<br>    return this<br>  }<br><br>  setEngine(engine: string): this {<br>    this.engine = engine<br>    return this<br>  }<br><br>  build(): Car {<br>    return this.builder(this.wheels, this.engine)<br>  }<br><br>}</pre><h3>Full Example</h3><p>This is now the full example of the builder pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d63d974fdbabccc7227542df16bcca72/href">https://medium.com/media/d63d974fdbabccc7227542df16bcca72/href</a></iframe><h3>Summary</h3><p>I tried to show you how to create a builder pattern for classes with private constructor and read only properties to prevent malicious modifications to your instances.</p><p>With the builder pattern you can simplify the creation process of complex objects and extract the creation rules to a dedicated class or function. With the director involved you can even outsource the steps of the instance creation further.</p><p>If this was helpful, please clap.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe7bad33008b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick & Dirty: Combine Streams in Node.js]]></title>
            <link>https://medium.com/@denis.loh/quick-dirty-combine-streams-in-node-js-0fac85dccd73?source=rss-aad7607062a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fac85dccd73</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[stream]]></category>
            <dc:creator><![CDATA[Denis Loh]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 08:42:27 GMT</pubDate>
            <atom:updated>2024-08-09T08:42:27.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_Tw4LdrRBiwL7BJGwG-Vrg.jpeg" /><figcaption>WikiMedia Commons by BiiJii</figcaption></figure><p>In our daily business it is sometimes required to apply some quick and dirty hacks as the project conditions do not allow sophisticated solutions.</p><p>I had the challenge where I got two Node.Streams which transformed some file input into JSON objects. The underlying logic of those streams are out of scope and thus unknown. The task was to combine these streams and pass it to the further processing. This means that we have to return a stream in our function, too.</p><p>So, that should be fairly easy:</p><pre>const combineStreams = sources: Readable[]): Readable =&gt; {<br>  let passStream = new PassThrough({ objectMode: true })<br>  for (const stream of sources) {<br>    const end = stream == sources.at(-1)<br>    passStream = stream.pipe(passStream, { end })<br>  }<br>  return passStream<br>}<br><br>const a: Readable = streamFromSomewhere()<br>const b: Readable = streamFromSomewhere()<br><br>const c = combineStreams([a, b])</pre><p>This function is basically just piping each stream into a PassThrought() which is a Duplex, which allows reading and writing into it. With the additional option end we can tell, that the PassThrough should end after the last stream, so the downstream consumers can end too.</p><p>Everything worked fine until one of the streams run into an error. The app crashed hard and thus, we applied an error handler:</p><pre>c.on(&#39;error&#39;, error =&gt; console.error(error))</pre><p>But the app was still crashing. But why?</p><h3>Error Handling with pipe()</h3><p>Unfortunately when using pipe you have to do this per every single pipe occurrence. The first idea was to use Node.Stream.pipeline(). This function receives a source stream, some transforms and a destination stream and last but not least a callback for error handling. However, our task was to forward everything to the downstream consumers. That included also the error handling. pipeline() is good when you have everything in place, but if you don’t have the destination stream, it doesn’t work. We need a custom solution.</p><p>We extend our combineStreamsto forward these errors to the PassThrough and then destroy the remaining streams.</p><pre>const combineStreams = (sources: Readable[]): Readable =&gt; {<br>  let passStream = new PassThrough({ objectMode: true })<br>  let errorOccurred = false<br>  for (const stream of sources) {<br>    if (errorOccurred) { <br>      stream.destroy()<br>      continue<br>    }<br><br>    const end = stream == sources.at(-1)<br>    passStream = stream<br>    .on(&#39;error&#39;, error =&gt; {<br>      passStream.destroy(error)<br>      errorOccurred = true<br>    })<br>    .pipe(passStream, { end })<br>  }<br><br>  return passStream<br>}<br><br>const a: Readable = streamFromSomewhere()<br>const b: Readable = streamFromSomewhere()<br><br>const c = combineStreams([a, b])<br><br>c.on(&#39;error&#39;, error =&gt; console.error(error))</pre><h3>Other options</h3><p>As long as Node.Stream.compose() which should do this job too, is experimental, you can also check 3rd-party libs like <a href="https://www.npmjs.com/package/multipipe">multipipe </a>, <a href="https://www.npmjs.com/package/multistream">multistream </a>or <a href="https://www.npmjs.com/package/stream-chain">stream-chain</a> whichever works best for you.</p><p>I hope you find this helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fac85dccd73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS Testing — Write Unit Tests for Observables]]></title>
            <link>https://medium.com/better-programming/rxjs-testing-write-unit-tests-for-observables-603af959e251?source=rss-aad7607062a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/603af959e251</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Denis Loh]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 10:30:12 GMT</pubDate>
            <atom:updated>2022-06-15T15:00:14.010Z</atom:updated>
            <content:encoded><![CDATA[<h4>Advance your unit testing skills by writing tests with the RxJS testing features.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NOPLpI2t91VPvGg9" /><figcaption>Photo by <a href="https://unsplash.com/@davynben?utm_source=medium&amp;utm_medium=referral">Davyn Ben</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>RxJS is a very powerful and cool set of tools to create reactive apps. When developing Angular applications, you will be very likely faced with RxJS, so I assume, you are familiar with how to use it.</p><p>However, when I started with Angular about three years ago, I got a couple of puzzled looks, when I asked them how to do testing with observables. Here is how I started and how I ended up writing unit tests for observables.</p><h3>Naïve Beginners Example</h3><p>Let’s start with a short example: A function, which takes a sentence and returns it in reverse order.</p><pre>export function myFunction1(x: string): Observable&lt;string&gt; {<br>  return of(x).pipe(<br>    map((x) =&gt; x.split(&#39; &#39;)),<br>    map((x) =&gt; x.reverse()),<br>    map((x) =&gt; x.join(&#39; &#39;))<br>  );<br>}</pre><p>I want to show you what the typical unit tests looked like when I started unit testing with observables:</p><pre>describe(&#39;RxJS&#39;, () =&gt; {<br>  it(&#39;returns simple value&#39;, () =&gt; {<br>    const y = myFunction1(&#39;humans eat tomatoes&#39;);</pre><pre>    y.subscribe((value) =&gt; expect(value).toBe(&#39;tomatoes eat humans&#39;));<br>  });<br>});</pre><p>Well, that was an easy one and to no surprise, it worked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*MnIUuf-QQxdMj9OzK2v4sA.png" /><figcaption>Successful test</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtxfdGlxEsG8%3Fstart%3D21%26feature%3Doembed%26start%3D21&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtxfdGlxEsG8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtxfdGlxEsG8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3950a8a0b5bc9a6a541b81820f1c907d/href">https://medium.com/media/3950a8a0b5bc9a6a541b81820f1c907d/href</a></iframe><p>If you don’t know the movie, it’s one of the worst horror movies in human history. Definitely worth watching it if you want to waste time.</p><p>Okay, let’s make our call asynchronous and add some delay:</p><pre>export function myFunction1(x: string): Observable&lt;string&gt; {<br>  return of(x).pipe(<br>    map((x) =&gt; x.split(&#39; &#39;)),<br>    map((x) =&gt; x.reverse()),<br>    map((x) =&gt; x.join(&#39; &#39;)),<br>    delay(10)<br>  );<br>}</pre><p>The test is obviously successful at a first glance, but when you look closer you can read, that the test has no expectations. This means that our test did not check anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*Mtk_3fhuXmIB3uKKVdHnEA.png" /><figcaption>Successful tests but without expectations.</figcaption></figure><p>You may also get this warning instead:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*r1s4Qh3pUuw_Ovr9wTkHvA.png" /><figcaption>Failed test due to timeout.</figcaption></figure><p>The test simply finished before the emitted value has been evaluated. A simple approach would be to make an asynchronous test out of it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c881ebca683ce2d37bedfd209d65bc5/href">https://medium.com/media/8c881ebca683ce2d37bedfd209d65bc5/href</a></iframe><p>Well done! It works. By the way, putting async in front of the test case callback will not work unless you run a promisable test case. On the other hand, you could use fakeAsync() from the <a href="https://angular.io/api/core/testing/fakeAsync">@angular/testing</a> package instead and use tick() to simulate a computation cycle.</p><p>But that’s not what we want to use for complex RxJS testing. We want to do it the right way: RxJS Testing</p><h3>Marble Diagrams</h3><p>So, let’s begin with some basics about marble diagrams. If you work with observables, you can consider the emission of the values like a stream or flow. When you apply operators to the stream, the values will change and the subsequent stream emit other values. You have some kind of input value, the according operator, which modifies it and the resulting output value (see the example of the map()operator below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPeRnQMWq9Wn69r6kDtfNg.png" /><figcaption>A simple marble diagram</figcaption></figure><p>Now you can assign each emitted value a letter like a, b and c. The end of the stream is symbolised with a pipe |. Errors are symbolised with a # . Now it may be the case, that there is some time passed between the emission the values. Time in observables can be represented with virtual frames, which are usually 1ms long and symbolised with a - or with a time progression value like 5s or 100ms . If multiple values are emitted at the same time frame, you can group them together using (). Some examples:</p><pre>a--b| // emits &#39;a&#39; then after ~40ms &#39;b&#39; and completes<br>(a|)  // emits &#39;a&#39; and completes immediately <br>a--b-a--c-a--| // emits a series of values<br>a---# // emits &#39;a&#39; and errors out after some time.</pre><h3>rxjs/testing</h3><p>RxJS comes with a handy toolset to test observables using marble diagrams as explained above.</p><p>First of all, we need a TestScheduler which we put at the top of our unit test file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f872d96f49db592a66fa59c87c5e9ef/href">https://medium.com/media/1f872d96f49db592a66fa59c87c5e9ef/href</a></iframe><p>Now, we can adjust our unit test again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5f1677f9aa663ae22a31ff5f23e9ed4/href">https://medium.com/media/c5f1677f9aa663ae22a31ff5f23e9ed4/href</a></iframe><p>The test is green again. Hurray! But let’s check what we added here. First of all, we define our expected marble diagram (1).</p><pre>----------(a|) // after 10 &#39;ticks&#39; the observable emits &#39;a&#39; and completes immediately after that.</pre><p>Instead of writing ---------- to represent 10ms of time, you can also directly write 10ms (a|) .</p><p>Then, we define our expected values (2), where we create an object structure with the keys from our marble diagram and the according value.</p><pre>const expectedValues = {<br>  a: &#39;tomatoes eat humans&#39;,<br>};</pre><p>And finally, we let the test scheduler run (3).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad79d19e99dc132bd08bda355398b847/href">https://medium.com/media/ad79d19e99dc132bd08bda355398b847/href</a></iframe><h3>Reading the Errors</h3><p>Now, when everything is fine, the unit test is green and we are all good. However, it is usually not the case, that things work out immediately. So, what do we get, if something goes wrong?</p><p>Let’s have a look at what our testing scheduler is actually comparing. So for a recap, this is our comparator:</p><pre>(actual, expected) =&gt; { return expect(actual).toEqual(expected) }</pre><p>It is a deep equality check of actual and expected, which are of type any , duh! <br>Anyway, this check is actually verifying a couple of things, which may happen during the subscription.</p><p>There are four types of issues:</p><ul><li>Length of frames (i.e., number of emitted items unexpected)</li><li>Number of frame (i.e., the expected time frame is unexpected)</li><li>Kind of frame (i.e., item, completion, error, subscription, unsubscription)</li><li>Frame value (i.e., emitted item value or error message)</li></ul><p>Assume, we forgot something in our function:</p><pre>export function myFunction1(x: string): Observable&lt;string&gt; {<br>  return of().pipe(           // we forgot to call of(x)<br>    map((x) =&gt; x.split(&#39; &#39;)),<br>    map((x) =&gt; x.reverse()),<br>    map((x) =&gt; x.join(&#39; &#39;)),<br>    delay(10)<br>  );<br>}</pre><p>This is, what we get then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*LFRc1yRNnXkK8Fyplb_22Q.png" /><figcaption>All kinds of errors</figcaption></figure><h4>Frames length incorrect</h4><pre>Expected $.length = 1 to equal 2.</pre><p>The above error tells, that we expected two frames, but got only one. So you get Expected $.length = X to equal Y , when you either emit more or less items than expected.</p><h4>Frame number incorrect</h4><pre>Expected $[0].frame = 0 to equal 10.</pre><p>The above error tells, that the frame number is incorrect. So you get Expected $[i].frame = X to equal Y , where i is the index of the frame, i.e. in our example the first frame.</p><h4>Frame type incorrect</h4><pre>Expected $[0].notification.kind = &#39;C&#39; to equal &#39;N&#39;.</pre><p>The above error tells, that the kind or type of frame is incorrect. So you get Expected $[i].notification.kind = &#39;...&#39; to equal &#39;...&#39; if the stream emitted another type of signal. Typical signals are:</p><ul><li>N = Emitted item</li><li>C = Completion</li><li>E = Error</li></ul><p>In our case, we expected an item on the first frame, but got a completion signal.</p><h4>Frame value incorrect</h4><pre>Expected $[0].notification.value = undefined to equal &#39;tomatoes eat humans&#39;.</pre><pre>Expected $[1] = undefined to equal Object({ frame: 10, notification: Object({ kind: &#39;C&#39;, value: undefined, error: undefined }) }).</pre><p>The above error tells, that the value of the frame / item is incorrect. So you get Expected $[i].notification.value = ... to equal ... if the actual value is incorrect. In the second error, you can see, that this kind of error applies also to a complete frame. In our example, the value of the first frame is undefined, but should hold ‘tomatoes eat humans’ and the second frame does not exist at all.</p><h3>What About Subjects?</h3><p>Sometimes you have event-driven use-cases where you have triggers, which causes any kind of action, and an event pipe, where you can listen for updates.</p><p>The following example is a BehaviorSubject with an initial value. Every time we call the add or minus function, we use the scan operator to calculate the sum out of the current value and the new value. The two functions might be bound to buttons and an input field, for example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/383374a1f726d791f0a35a5b6955a199/href">https://medium.com/media/383374a1f726d791f0a35a5b6955a199/href</a></iframe><p>Let’s write the unit test for this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e0f76b85499285694e84ad06e8d0054/href">https://medium.com/media/4e0f76b85499285694e84ad06e8d0054/href</a></iframe><p>This is the result, which is good so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*8Movo-OiYxoMddgdaqxXHg.png" /><figcaption>Successful test for subjects</figcaption></figure><p>But how do we now trigger the function calls? A naive implementation would be something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7acf267af6b6c8b074f85013d8ffeb2c/href">https://medium.com/media/7acf267af6b6c8b074f85013d8ffeb2c/href</a></iframe><p>But this will not work. There are no items emitted at all. Why that? Essentially because the testScheduler is running in its own synchronous scope and therefore the two tasks of setTimeout are executed after the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*KuUeCCbRjkJzfac4KzpopA.png" /><figcaption>Failed test when using triggers</figcaption></figure><p>To fix this, we have to run the triggers within the testScheduler scope. The testScheduler provides some additional helpers beside the expectObservable . You can find the documentation about them here: <a href="https://rxjs.dev/guide/testing/marble-testing#api">https://rxjs.dev/guide/testing/marble-testing#api</a></p><p>With triggerMarbles and triggerValues we can create function calls, which will happen at the exact time frame, we need it.</p><pre>const triggerMarbles = &#39;-abcabc&#39;;<br>const triggerValues = {<br>  a: () =&gt; add(5),<br>  b: () =&gt; add(2),<br>  c: () =&gt; minus(7),<br>};</pre><p>We will now need the cold helper to run these triggers:</p><pre>testScheduler.run(({ expectObservable, cold }) =&gt; {<br>  ...<br>  expectObservable(<br>    cold(triggerMarbles, triggerValues).pipe(tap(fn =&gt; fn()))<br>  );<br>});</pre><p>expectObservable subscribes (and also unsubscribes) to our cold observable. With the .pipe(tap(fn =&gt; fn())) we run the corresponding trigger function.</p><p>Now, we can adjust the expected output:</p><pre>const expectedMarbles = &#39;abcabca&#39;;<br>const expectedValues = {<br>  a: 0,<br>  b: 5,<br>  c: 7,<br>};</pre><p>Putting everything together, we have this unit test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef4eab93182eb52db0b9d9e5dae41aaa/href">https://medium.com/media/ef4eab93182eb52db0b9d9e5dae41aaa/href</a></iframe><h3>Known Limitations</h3><p>You can read about the known limitations here: <a href="https://rxjs.dev/guide/testing/marble-testing#known-issues">Known issues</a>. However, I want to summarise some of them, because they may be not that obvious.</p><h4>Promises / setTimeout()</h4><p>Promises are not supported as an observable source, i.e. something like the code below cannot be asserted with the testScheduler:</p><pre>from(Promise.resolve(&#39;something&#39;))</pre><p>This means, that also every API, which returns a promise like fetch() or async functions which are wrapped into observables. To make these work, you have to have to fall back to asynchronous testing as explained above, e.g. using done().</p><h3>Fin!</h3><p>You can find the examples above in this stackblitz project here: <a href="https://stackblitz.com/edit/rxjs-testing-kit?file=main.ts">https://stackblitz.com/edit/rxjs-testing-kit?file=main.ts</a></p><p>I hope this will help you to write unit tests with RxJS observables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_oIIrKQw9mJ85uDS" /><figcaption>Photo by <a href="https://unsplash.com/@theblowup?utm_source=medium&amp;utm_medium=referral">the blowup</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=603af959e251" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/rxjs-testing-write-unit-tests-for-observables-603af959e251">RxJS Testing — Write Unit Tests for Observables</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I use decorators for coersion in Angular]]></title>
            <link>https://medium.com/@denis.loh/why-i-use-decorators-for-coersion-in-angular-f4d364f82255?source=rss-aad7607062a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4d364f82255</guid>
            <category><![CDATA[coercion]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[property-binding]]></category>
            <category><![CDATA[decorators]]></category>
            <dc:creator><![CDATA[Denis Loh]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 12:53:34 GMT</pubDate>
            <atom:updated>2022-03-18T13:06:57.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WmOv75qGruZoRCKE" /><figcaption>Photo by <a href="https://unsplash.com/@madhatterzone?utm_source=medium&amp;utm_medium=referral">Manja Vitolic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When you write components you will typically come across the requirement of providing input fields, which shall be used as an attribute flag in your template code.</p><p>So, let’s create a small example:</p><pre>@Component({<br>  selector: &#39;my-component&#39;,<br>  template: `<br>    &lt;div&gt;{{myValue | json}}&lt;/div&gt;<br>  `<br>})<br>export class MyComponent {<br>  @Input() myValue: boolean<br>}</pre><pre>@Component({<br>template: `<br>  &lt;my-component [myValue]=&quot;true&quot;&gt;&lt;/my-component&gt;<br>`<br>})</pre><pre>export class AppComponent {<br>}</pre><p>Well, this will predictably and not surprisingly print true . But now we want to use something like this:</p><pre>@Component({<br>template: `<br>&lt;my-component myValue&gt;&lt;/my-component&gt;<br>`<br>})</pre><pre>export class AppComponent {<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*57JXItqVBPSgjsYh" /><figcaption>Photo by <a href="https://unsplash.com/@kingmaphotos?utm_source=medium&amp;utm_medium=referral">Jeff Kingma</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is what you will get then:</p><pre>Error in <strong>src/app/app.component.html</strong> (1:15)</pre><pre>Type &#39;string&#39; is not assignable to type &#39;boolean&#39;.</pre><p>So, what’s wrong with that? When you just use the input field as an attribute without property binding, it will be treated as a string literal¹. That however means, our property myValue will receive an empty string &#39;&#39; .</p><h3>Coerse to a boolean value</h3><p>To solve this issue, we have to accept and handle also string values in our MyComponent . Let’s just enhance our component a bit:</p><pre>@Component({<br>  selector: &#39;my-component&#39;,<br>  template: `&lt;div&gt;{{ myValue | json }}&lt;/div&gt;`<br>})</pre><pre>export class MyComponent  {<br>  private _myValue: boolean = false;</pre><pre>  @Input()<br>  get myValue(): any { return this._myValue }<br>  set myValue(value: any) { this._myValue = !!value }<br>}</pre><p>But nah! It still doesn’t work:</p><pre>false</pre><p>While using !! works most of the times to coerse any value into boolean, it doesn’t work here as we expect an empty string &quot;&quot; to be true . So we have to adjust it again a bit:</p><pre>set myValue(value: any) { <br>  this._myValue = value != null &amp;&amp; `${value}` !== &#39;false&#39;<br>}</pre><p>Oh yeah! It works:</p><pre>true</pre><p>Luckily, you do not have to care about this coerse function that much, because there is already a helper function in the Angular CDK, which is called coerceBooleanProperty²:</p><pre>...<br>import {<br>  coerceBooleanProperty,<br>  BooleanInput<br>} from &#39;@angular/cdk/coercion&#39;;</pre><pre>@Component({<br>  selector: &#39;my-component&#39;,<br>  template: `&lt;div&gt;{{ myValue | json }}&lt;/div&gt;`<br>})<br>export class MyComponent  {<br>  private _myValue: boolean = false;</pre><pre>  @Input()<br>  get myValue(): BooleanInput { return this._myValue }<br>  set myValue(value: BooleanInput) {<br>    this._myValue = coerceBooleanProperty(value)<br>  }</pre><pre>}</pre><p>But hey, this is quite a lot of boiler plate for a simple attribute, right? Can’t we do it more readable and shorter? Yes, we can!</p><h3>Use decorators</h3><p>With decorators³ we are able to generate the required helper property and reduce it to a single line of code. Let’s see how it’s done.</p><p>First we have to create the property decorator factory:</p><pre>export function createPropertyDecorator&lt;T&gt;(<br>  fn: (value: any, ...props:any) =&gt; T, ...props:any<br>) : PropertyDecorator {<br>  return (target: Object, propertyKey: string | symbol) =&gt; {<br>    const tmpKey = `${String(propertyKey)}Tmp`</pre><pre>    function getter(this: any) : T {<br>      return this[tmpKey]<br>    }</pre><pre>    function setter(this: any, value: any) {<br>      this[tmpKey] = fn(value, props)<br>    }</pre><pre>    Object.defineProperty(target, tmpKey, {<br>      value: undefined,<br>      writable: true,<br>      enumerable: true,<br>      configurable: true<br>    })</pre><pre>    Object.defineProperty(target, propertyKey, {<br>      get: getter,<br>      set: setter,<br>      enumerable: true,<br>      configurable: true<br>    })<br>  }<br>}</pre><p>This factory creates a new decorator, which overrides our property with a customised getter and setter. It also constructs a storage property, where the result is held. Whenever we set our property, it will call the setter of our decorator and internally applies our converter function.</p><p>And now we write the actual decorator:</p><pre>export function coerceToBoolean(value: any): boolean {<br>  return value != null &amp;&amp; `${value}` !== &#39;false&#39;<br>}</pre><pre>export function ToBoolean() : PropertyDecorator {<br>  return createPropertyDecorator&lt;boolean&gt;(coerceToBoolean)<br>}</pre><p>Finally, we adjust our component again:</p><pre><a href="http://twitter.com/Component">@Component</a>({<br>  selector: &#39;my-component&#39;,<br>  template: `&lt;div&gt;{{ myValue | json }}&lt;/div&gt;`<br>})<br>export class MyComponent  {<br>  @ToBoolean() @Input() myValue: boolean | string<br>}</pre><p>We have to use boolean | string here to stay type-safe, but all values will be boolean.</p><p>You can find the working example on StackBlitz here: <a href="https://angular-ivy-btvkrv.stackblitz.io/">https://angular-ivy-btvkrv.stackblitz.io</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JRMI839j4vZXxao5" /><figcaption>Photo by <a href="https://unsplash.com/@alexas_fotos?utm_source=medium&amp;utm_medium=referral">Alexas_Fotos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>One last remark…</h3><p>While the Angular CDK function coerceBooleanProperty does it’s job, it has one particular flaw:</p><pre>coerceBooleanProperty(&quot;0&quot;); // returns true!</pre><p>So, to solve this issue, we have to adjust our own coerce function as such:</p><pre>export function coerceToBoolean(value: any): boolean {<br>  return value != null &amp;&amp; `${value}` !== &#39;false&#39; &amp;&amp; value != &#39;0&#39;;<br>}</pre><p>That’s it!</p><p>I hope this helps someone.</p><p>[1] Angular — Binding to a property: <a href="https://angular.io/guide/property-binding#binding-to-a-property">https://angular.io/guide/property-binding#binding-to-a-property</a><br>[2] Angular CDK — Coersion: <a href="https://material.angular.io/cdk/coercion/overview">https://material.angular.io/cdk/coercion/overview</a><br>[3] Typescript Decorators: <a href="https://www.typescriptlang.org/docs/handbook/decorators.html">https://www.typescriptlang.org/docs/handbook/decorators.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4d364f82255" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Covid cost me my place of work]]></title>
            <link>https://medium.com/@denis.loh/covid-cost-me-my-place-of-work-b1a1f96d0add?source=rss-aad7607062a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1a1f96d0add</guid>
            <category><![CDATA[office-culture]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[new-working-method]]></category>
            <category><![CDATA[home-office]]></category>
            <dc:creator><![CDATA[Denis Loh]]></dc:creator>
            <pubDate>Thu, 17 Mar 2022 09:46:23 GMT</pubDate>
            <atom:updated>2022-03-17T09:46:23.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RH4oO9KnQnnK9Gw6" /><figcaption>Photo by <a href="https://unsplash.com/@jaypme4?utm_source=medium&amp;utm_medium=referral">Joao paulo m ramos paulo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Back in 2013 our company expanded and moved into another floor in our office building in the beautiful city of Dresden in Silicon Saxony. That floor was previously used by the youth welfare office and thus had the charm of a typical office building: grey in grey, long and never-ending hallways with large doors and artificial lighting.</p><p>While we could live with that — other floors are still in that flavor — we settled a team across all different kind of employees: developers, managers, consultants, facility managers, etc. to build something new. We launched the concept of modern work spaces with large open spaced and colourful offices, many collaboration spaces, chill-down areas and sporting elements like swings, table-soccer or punching-balls. But the primary conceptional change was:</p><p><em>You don’t own your desk.</em></p><h3>Mind Change required</h3><p>While we have been able to address all the changes with practical solutions, like moving from desktop computers to laptops or migrating from hard phones to soft phones, one thing was extremely hard to migrate: the mind of the people. It took a couple of months to move the people of the old office space with individual desks with plants and photos to a shared desk, which had to be set up before and cleaned up after your work.</p><p>We were equipped with our personal “work gear”:</p><ul><li>Laptop</li><li>Keyboard and mouse</li><li>Headset</li><li>Laptop bag</li></ul><p>So all this and likely also some other personal equipment had to be carried to your place of work.</p><p>People were hating this concept at the beginning as it was taking a seriously amount of time in your daily business before your were able to work. Over the time, we slipped into the old behaviour of having individual desks, which have been used by the same workers, especially developers, over weeks. But was it that bad? I’d say no.</p><p>The whole idea behind shared desks is that you reduce the amount of office space required to hold an individual desk for every employee and provide only as much space as required to hold an average of available people in the office. There is always someone on leave for various reasons, sickness, holidays, business trips. Why holding an unused desk for those?</p><p>For this, we introduced a desk-to-employee ratio of about 1.2 to 1.5, which means that each desk is shared with 1.2 to 1.5 coworker. So, over the year you have to share your desk with another colleague for about 40 to 100 days. But even if you consider all your holidays and sick-leaves, there might be peaks, where all the people are in and want to work at a desk, right?</p><p>Yes and no, it never came to such a situation, where every single desk was occupied. So it was only a theoretical fear that the people had to sit close to each-other at a single desk like I did in school, when I as a left-hander was sitting next to a right-hander and poked each-other when writing.</p><h3>Shared teams</h3><p>As we have also locations in other cities like Berlin, Hamburg, Bonn or even other countries, we had also to cope with shared teams. You had to consider how you integrate these people into your project without leaving them behind. We started early using tools like Cisco WebEx or Microsoft Skype for Business for screen sharing and quick calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3FbmabJoogimoONR" /><figcaption>Photo by <a href="https://unsplash.com/@surface?utm_source=medium&amp;utm_medium=referral">Surface</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When I started a big international project back in 2019, we had colleagues and team-members in various countries: India, Brazil, UK, Sweden, etc. So there was with no doubt no other possibility than doing all the meetings virtually.</p><p>And then, in the beginning of 2020 Covid kicked in and vanished our work spaces as we used to know them not only for us who have get used to the new work environment but to all employees.</p><p>I moved to into Home office in Feb. 2020 to mitigate the risk of an infection in our team, so that half the team was able to work in the office and the other half worked from home. Since then, I was only about 6 times in the office.</p><h3>Prepared for the next big change</h3><p>So sitting in our child’s room for a couple of months now I was wondering how Covid might impact world of working in future. And indeed, the things were changing rapidly. Our company was impressively well prepared to cope the situation and we were able to quickly send all employees to work from home. We had the gear, we had the tools and thus just started working from whereever you want.</p><p>The offices had to reduce the total capacity to about 25% of the available desks. But the few times I was in the office, it was like going to work at weekends. No-one — I mean this literally — was there on the whole floor. So it became quite strange to be alone in this large building and I was questioning: why should I be here? Free coffee, which doesn’t even taste well? Travelling from home to office and back although it rains cats and dogs?</p><p>I experienced myself a significant improvement on my productivity while I was at home compared to how I worked in the office. I was able to work more concentrated and focused, yet still had the ability to have breaks whenever I want.</p><p>Beside the fact, that you should own a proper table or desk with a comfortable chair, people are saying, that they still have some troubles with working from home because they are taking too much work into their private life with no proper cut after work. This is how I did it:</p><h3>Simulate way to work</h3><p>If you can’t do the cut after works, go outside and have a walk. Free your mind after with a fixed schedule to calm down. In our case, we had to take our child to and from the nursery every morning and afternoon. This short travel was enough to have a hard cut in your business day which you should not miss — otherwise your child will be very angry with you.</p><p>When you leave home consider this as like you leave the office. Drop the thoughts behind you and most importantly: do not start working again once you are back. If you do so, you will likely end up in the middle of the night in front of your computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qiu8frKNM4jAPbEz" /><figcaption>Photo by <a href="https://unsplash.com/@acasetta?utm_source=medium&amp;utm_medium=referral">Alberto Casetta</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>New Normal</h3><p>Now, with Covid almost being over, there is that imminent question: will we all have to go back to office now? Our company said quite clearly: no, if you don’t have to. And I am very happy about this decision. If there is no specific need of crowding all these people in a cube farm with 40 or more workers, why should they have to waive all the advantages of flexible working? Your child is sick? Stay at home and take care for it! You need to collaborate with other colleagues about a complex topic? Come together and do a workshop in the office.</p><p>The question is how we balance office time with working from home. The most studies I read so far about the disadvantages of home office were originated by employers who feared the loss of control over their employees. It might be true, that there are some people misusing this flexibility, but you can’t control them all the time in the office too, right? And if my boss would have to control me, whatever I do, it would have been a toxic relation anyhow.</p><p>So, in my ideal world of the new normal we will still have office spaces, where those can work, who are not able to facilitate an own desk in a tiny flat or are more efficient when they are surrounded by other people. But the offices will have more collaboration spaces, which invite you to do workshops rather than the daily business work. The office is then a place to come together. Rather going to work to just work, it is a well-prepared and planned event to have some collaborated outcome, which is imported not just for you, but for everyone in your team. You can still scrub your tasks home alone — or whereever you want to work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1a1f96d0add" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>