<?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 Tomasz Świstak on Medium]]></title>
        <description><![CDATA[Stories by Tomasz Świstak on Medium]]></description>
        <link>https://medium.com/@tomasz-swistak?source=rss-80cd18546a46------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*D225VWhud-H-Wljh.</url>
            <title>Stories by Tomasz Świstak on Medium</title>
            <link>https://medium.com/@tomasz-swistak?source=rss-80cd18546a46------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:27:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tomasz-swistak/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[How to increase your frontend app’s performance — 5 coding tips]]></title>
            <link>https://itnext.io/how-to-increase-your-frontend-apps-performance-5-coding-tips-d92a56ca9c24?source=rss-80cd18546a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/d92a56ca9c24</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tomasz Świstak]]></dc:creator>
            <pubDate>Tue, 18 Jun 2019 07:44:30 GMT</pubDate>
            <atom:updated>2021-06-24T11:22:51.267Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to increase your frontend app’s performance — 5 coding tips</h3><p>In many of my frontend projects, at some point I’ve encountered the issue of the app’s performance decreasing. Things like this happen — it’s normal when the complexity of a solution increases. But still, it’s something that we developers need to take care of. In this article I’d like to show you 5 tips to help optimize your app (things I’ve done in my projects). Some of them may seem obvious, some of them are programming basics, but I think that it’s always good to refresh our memory. Each tip is backed by benchmarks that you can run on your own and check performance by yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymhw88P7XzFPN69NLdZ42g.jpeg" /><figcaption>Image by <a href="https://dribbble.com/p_niewiadomska">Paulina Niewiadomska</a></figcaption></figure><h3>Before you read these tips</h3><p>Remember one important thing: when your code doesn’t need optimizations, don’t mess with it. You should always write code that is fast, but it should also be readable for other developers, because there is almost always a faster way to achieve something. Donald Knuth wrote in “Computer Programming as an Art” the most important thing you should know about optimizing code:</p><blockquote>The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; <strong>premature optimization is the root of all evil</strong> (or at least most of it) in programming.</blockquote><h3>1. Use objects/maps for lookups instead of arrays</h3><p>When we’re working with data, we can often have situations like “find an object, do something with it, find another object…” Since the most common JS data structure is that of an array, it’s normal for our data to be stored in one. However, each time we want to find something in an array we need to use methods like find, indexOf, filter, or we can iterate with loops — so we must go from the start to the end of a structure. So, we will use a linear search, which has complexity O(n) (it means that in the worst case we will need to perform as many comparisons as there are elements in an array). Although it may be not noticeable when we do it a few times in small arrays, it will absolutely affect performance when there are many elements and we need to do it many times.</p><p>In such a scenario, it may be a good idea to convert an array to an object or map and perform lookups based on keys. In these data structures we can access an element with O(1) complexity, so it will always be just one call to memory, no matter the size. That’s because there’s a data structure behind those two called a <a href="https://en.wikipedia.org/wiki/Hash_table">hash table</a>.</p><p>You can perform a benchmark here: <a href="https://jsperf.com/finding-element-object-vs-map-vs-array/1">https://jsperf.com/finding-element-object-vs-map-vs-array/1</a>. Below you can see my results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYRf8t3WYkqvufOCz9x05g.png" /></figure><p>The difference is significant — for map and object I obtained millions of operations per second, when in an array the best result was slightly above 100 operations. Of course, it doesn’t take the data conversion into account, but it will still be a lot faster, even when you have to convert.</p><h3>2. Use “if” conditions instead of catching exceptions</h3><p>Sometimes people find it easier to omit null checking and just catch exceptions when something doesn’t exist. Of course, that’s a bad practice and no one should do it. So, if you have sections like this in your code, just replace them. Naturally you may want to see the benchmarks to be 100% sure. In my benchmark, I’ve decided to check three ways — try-catch expression, if condition and short-circuit evaluation.</p><p>Here’s a benchmark: <a href="https://jsperf.com/try-catch-vs-conditions/1">https://jsperf.com/try-catch-vs-conditions/1</a>. Below you can see my results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZdZC0J0xo1Rw-O_dZ25Ug.png" /></figure><p>I think it goes without saying that it’s always better to perform the null check. Also, as you can see, there’s nearly no difference between if condition and short-circuit evaluation, so just use whatever suits you more.</p><h3>3. Use as few loops as you can</h3><p>This is another obvious but potentially controversial notion. Since we have all those great functions on arrays like map, filter, reduce, it’s very tempting to use them. They usually make code cleaner and more readable to other developers. But when performance goes down, we may seek to flatten it. I decided to create two cases: filter then map and filter than reduce. I test each of these cases with a function chain, forEach and a traditional for loop. Why these two? As you will see, the benefits may not be very significant. Additionally, for the second one I decided also to do filtering while reducing.</p><p>Benchmark for filter then map: <a href="https://jsperf.com/array-function-chains-vs-single-loop-filter-map/1">https://jsperf.com/array-function-chains-vs-single-loop-filter-map/1</a>. And my results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIRmwEPmSZMxUr7U3Q0-qQ.png" /></figure><p>Of course, a single loop is faster, but the difference is not that big. That’s because of the push operation, which we don’t need to do while mapping. So, in this case you may want to consider if it’s really necessary.</p><p>So, let’s now check filter with reduce: <a href="https://jsperf.com/array-function-chains-vs-single-loop-filter-reduce/1">https://jsperf.com/array-function-chains-vs-single-loop-filter-reduce/1</a>. Here are my results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Alaxe4_rAwZTpmjJJ1C2Q.png" /></figure><p>Here the difference is more significant. Flattening two functions into one gave us nearly 100% faster execution time. However, the change to a traditional for loop gives a huge speed boost.</p><h3>4. Use basic for loops</h3><p>This one may also be a bit controversial, because developers love function loops. They look nice and can provide a nice workflow. However, using them is not as efficient as using traditional loops. I think that earlier you could see the difference in using for loops, but let’s look at it on a separate benchmark: <a href="https://jsperf.com/for-loops-in-few-different-ways/">https://jsperf.com/for-loops-in-few-different-ways/</a>. As you can see, along with the built-in ways, I’ve also tested forEach from Lodash and each from jQuery. Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abt4mktB7PI4Ah5vyGZh_A.png" /></figure><p>Once again, we can see that the most basic for loop is much faster than any other approach. However, they are only good for arrays. In case of other iterables, we should use forEach, for…of or iterator directly. As for for…in — well, better not use it. Only if there’s absolutely no other way. Also, please remember that because for…in takes all of object properties (and in an array, properties are indexes) it may lead to unpredictable results. Surprisingly, methods from Lodash and jQuery aren’t that bad from performance’s point-of-view, so you don’t need to worry about using them in some cases instead of built-in forEach (what’s surprising in the benchmark, one from Lodash performs better than built-in).</p><h3>5. Use built-in DOM functions</h3><p>Have you ever been looking at someone’s JS code and seen that jQuery was imported just to manipulate DOM? I’m pretty sure that you have, since it’s one of the most popular JavaScript libraries. Of course, using libraries to manage DOM is not bad — we use React or Angular nowadays, and they do the same thing. However, some people are convinced that they have to use jQuery for the simple operation of taking element from DOM and performing minor modifications to it.</p><p>Here’s the benchmark comparing jQuery and native DOM functions for three different use cases: <a href="https://jsperf.com/native-dom-functions-vs-jquery/1">https://jsperf.com/native-dom-functions-vs-jquery/1</a>. Below are my results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpcFCcmD3XdHDTGcC0Xkqg.png" /></figure><p>Again, the most basic functions — getElementById and getElementsByClassName — are the fastest way to traverse DOM. For id and advanced selectors, querySelector is still faster than jQuery. There’s just one case where querySelectorAll is slower than jQuery (getting elements by class name). If you want more information on how to replace jQuery, you may want to check out <a href="http://youmightnotneedjquery.com/">http://youmightnotneedjquery.com</a>.</p><p>Of course, remember that when you’re using a library for DOM management, it’s highly recommended to stick to it. But the truth is that for simple cases it’s not at all necessary.</p><h3>What’s next?</h3><p>Those five tips are for sure a good start to write faster code in JavaScript. If you want to go further, here are some things to check out next:</p><p>1. Read about optimizing JavaScript bundles with Webpack. That’s a tremendously broad topic but doing it properly can boost significantly the loading times of your applications.</p><p>2. Learn about data structures, basic algorithms and their complexity. Many consider it to be merely theoretical knowledge, but in the first tip we saw how it works in practice.</p><p>3. Browse test cases on the <a href="https://jsperf.com/popular">jsPerf</a> page. It’s a great place where you can compare different ways of achieving the same thing in JavaScript, but with the most important practical information — specifics about the time difference.</p><blockquote>Post was also published on the <a href="https://www.synergycodes.com/blog/how-to-increase-your-frontend-apps-performance">blog of Synergy Codes</a> — a software house specializing in process visualization, mapping and modeling.<br>Are you interested in creating data visualization apps? <a href="https://synergycodes.com/gojs-ebook/">Click here to learn about GoJS library</a>!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d92a56ca9c24" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-increase-your-frontend-apps-performance-5-coding-tips-d92a56ca9c24">How to increase your frontend app’s performance — 5 coding tips</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency injection in React using InversifyJS. Now with React Hooks]]></title>
            <link>https://itnext.io/dependency-injection-in-react-using-inversifyjs-now-with-react-hooks-64f7f077cde6?source=rss-80cd18546a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/64f7f077cde6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Tomasz Świstak]]></dc:creator>
            <pubDate>Fri, 17 May 2019 10:47:36 GMT</pubDate>
            <atom:updated>2021-06-24T11:22:23.475Z</atom:updated>
            <content:encoded><![CDATA[<p>Nearly a year ago <a href="https://itnext.io/dependency-injection-in-react-using-inversifyjs-a38ff0c6601">I wrote an article about dependency injection in React</a>. I showed how to inject dependencies into class components from InversifyJS containers. Since then we’ve witnessed the release of one of the most anticipated React features — Hooks. If you’ve never heard about them, you should definitely go to <a href="https://reactjs.org/docs/hooks-intro.html">docs</a> and learn about them. The key thing is that we can now do a lot more with functional components and they are really user-friendly. In this article, I’d like to show you how easy it is to use InversifyJS with Hooks with a very simple example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMk5vIkDsZXovkPy_AU-Vw.jpeg" /></figure><h3>Example project</h3><p>The project we’ll be working on is nearly the same as the one from the previous article. The only difference is that I’ve refactored the Hello component to be functional. Everything’s done in TypeScript, but you can do it almost the same way in pure JavaScript (there are some differences in decorators usage, but these are covered in <a href="https://github.com/inversify/InversifyJS/blob/master/wiki/basic_js_example.md">Inversify’s docs</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21bf1950990e4e8efb18dff45f758b3a/href">https://medium.com/media/21bf1950990e4e8efb18dff45f758b3a/href</a></iframe><p>For more information about that code, I recommend reading the “Example project” section of a <a href="https://itnext.io/dependency-injection-in-react-using-inversifyjs-a38ff0c6601?gi=a349e1f65b62">previous article</a>.</p><h3>Creating our own injection provider</h3><p>To accomplish this task, we will mainly use two React functionalities — Context API (since v.16.3) and React Hooks (since v.16.8).</p><p>Context API is the way to pass data through the whole component tree without using props. You can read about the details in <a href="https://reactjs.org/docs/context.html">docs</a>, since I don’t want to go deep into the weeds of Context here. You’ve probably used it already in an indirect way — a lot of popular libraries use it (react-redux, styled-components, etc.). If a library tells you to wrap everything on the root level with a provider component, then it probably uses Context.</p><p>Our injection provider will comprise two elements:</p><ul><li>A provider component that will wrap everything on the root level, where the developer will provide a reference to Inversify’s container.</li><li>A Hook for injecting dependency into component.</li></ul><h3>Provider component</h3><p>We will use Context to create a provider component. First, we need to create a new Context with the createContext function. This returns an object containing two ready components — Provider and Consumer. Provider is a top-level component which is used to send things down into React’s tree, and Consumer uses that data. What does this mean for us? That we can use it directly to accomplish our task. An example of how this can be done is in Listing 2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23c3b32ac66969d0f7cf0c4eef3b9864/href">https://medium.com/media/23c3b32ac66969d0f7cf0c4eef3b9864/href</a></iframe><p>Pretty simple, isn’t it? If you remember inversify-react or react-inversify from the previous article, you will surely know how to use it. It’s exactly the same component, but this time it’s been made by us. Listing 3 shows us how to use it in the code on the application’s root level.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d2c83b9a08e1b8502a652d58d0be3f5/href">https://medium.com/media/0d2c83b9a08e1b8502a652d58d0be3f5/href</a></iframe><h3>Injection hook</h3><p>Now we need a way to get the object from Inversify’s container. We want to do it as a function which will work as a React Hook, and it should use the container provided by the user in the Provider component. So, how are we to achieve this? As you likely remember, after creating Context we had an object which contained a Provider and Consumer. Usually, the Consumer is used as a component to access the data in a context through it. However, since we have React Hooks, we don’t need to use a Consumer. One of the most important Hooks built into React is <a href="https://reactjs.org/docs/hooks-reference.html#usecontext">useContext</a>. It does a simple thing — it returns the current context value and subscribes to its changes. In Context we have the container instance, so we can use any method from it that we need (in our case the method will be <em>get</em>, but you may also want to create an additional hook with <em>getAll</em> to simulate multiInject). Of course, the developer should provide the identifier to our Hook as an argument so that Inversify will be able to identify what we need. You can see a very simple implementation of this in Listing 4.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd0d690f1a6d3cbc351dcdd37cd38bd0/href">https://medium.com/media/dd0d690f1a6d3cbc351dcdd37cd38bd0/href</a></iframe><p>Now we can safely use it in our example app, in Hello.tsx, as shown on Listing 5.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c00344613393824b9b7d8e5773e45af/href">https://medium.com/media/3c00344613393824b9b7d8e5773e45af/href</a></iframe><p>As you can see, in a few lines of code we were able to create the whole provider for the dependency injection with very simple usage. Of course, it can be extended — you may want to add a hook for multi-injection or a higher order component to use in class components.</p><p>You can find the whole example on my GitHub:</p><p><a href="https://github.com/tswistak/react-hooks-with-inversify">tswistak/react-hooks-with-inversify</a></p><h3>Q&amp;A</h3><p>Since it’s so simple, I’m sure there are a lot of questions about it. I’ve thought about a few cases and want to give you answers in the same article.</p><h4>Why use such boilerplate when you can access the container directly from the component?</h4><p>That’s to keep a single source of truth and not to make the component dependent on a specific container. In one code base we may have many containers (e.g. each route has a different one), but components may be shared between them.</p><h4>So we shouldn’t use the libraries that you mentioned in the previous article?</h4><p>Of course not! It’s just to show an alternative way of achieving the same thing. It’s so simple that you may want to consider using it, but I’m not forcing you to do anything.</p><h4>I want to use a library for that, but are there any with Hooks?</h4><p>Yes, there are. While I was writing this article, I wanted to check whether someone had already implemented the idea. I found a very nice library — <a href="https://www.npmjs.com/package/react-injection">react-injection</a>. It gives us both a higher-order component and a hook to provide injections into components. If you want to use a library to connect Inversify with React using hooks, this may be a good way to go.</p><blockquote>Post was also published on the <a href="https://www.synergycodes.com/blog/dependency-injection-using-inversifyjs-with-hooks">blog of Synergy Codes</a> — a software house specializing in process visualization, mapping and modeling.<br>Are you interested in creating data visualization apps? <a href="https://synergycodes.com/gojs-ebook/">Click here to learn about GoJS library</a>!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64f7f077cde6" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/dependency-injection-in-react-using-inversifyjs-now-with-react-hooks-64f7f077cde6">Dependency injection in React using InversifyJS. Now with React Hooks</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding any in TypeScript — advanced types and their usage]]></title>
            <link>https://itnext.io/avoiding-any-in-typescript-advanced-types-and-their-usage-691b02ac345a?source=rss-80cd18546a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/691b02ac345a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tomasz Świstak]]></dc:creator>
            <pubDate>Wed, 16 Jan 2019 12:01:23 GMT</pubDate>
            <atom:updated>2021-06-24T11:22:03.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>Avoiding any in TypeScript — advanced types and their usage</h3><p>TypeScript gives JavaScript developers an opportunity to provide strict types in a code. However, due to the nature of JavaScript, in some cases providing accurate types isn’t a simple task. In such situations programmers are tempted to use <em>any</em> — a typing picklock which allows the user to store anything in it. In this article I’d like to show some built-in types and built-in TypeScript features which you can use to avoid <em>any</em> or to simplify some custom typings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XClR820xvc5FKQAa_ppDIw.jpeg" /></figure><h3>JavaScript objects</h3><p>Probably, nearly every JavaScript developer at some time has used an object as a map-like collection. However, with strict types it may not be that obvious how to type this (especially with the <a href="https://palantir.github.io/tslint/rules/no-string-literal/">no-string-literal</a> TSLint rule). The first go-to option is <em>any</em>, but we are losing information of value type. So, we may strictly type an interface with certain keys — but this way we can’t add anything to the object. Another option is <em>Object</em> or <em>{}</em>, but this means “empty object,” so we can’t set anything in it. So, what’s the standard way?</p><p><em>Record</em></p><p>Let’s see the definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80fc0f3c92ff1e9ccfe0e4b3adfdc0b4/href">https://medium.com/media/80fc0f3c92ff1e9ccfe0e4b3adfdc0b4/href</a></iframe><p>And the usage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/078c09eeffc452fba84a4c5a0d569585/href">https://medium.com/media/078c09eeffc452fba84a4c5a0d569585/href</a></iframe><p>As you can see, it means that the developer can enter any key, but the value has to be of a specific type. What’s more, we can combine it with other types, therefore making dictionaries with some pre-defined keys (of even different value types!) visible by IntelliSense, e.g.:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d96f7b9e579b8d4439d13a44e036c38f/href">https://medium.com/media/d96f7b9e579b8d4439d13a44e036c38f/href</a></iframe><p>I don’t think I need to write about the practical usage of this. Of course, we have a built-in ES6 collection called “Map” that offers a much better experience for dictionaries, but according to <a href="https://jsperf.com/es6-map-vs-object-properties/73">benchmarks</a>, when we only want to set and get values, it’s faster to use objects (Record).</p><h3>Mass modifiers of other type’s properties</h3><p>What to do, when we already have a type with defined properties, but we don’t like how it is defined? Maybe we want all properties to be optional, required, or read only? TypeScript also has it covered with the types <em>Partial</em>, <em>Required</em> and <em>Readonly</em>. Let’s see their definitions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/375e73972f73086057b3c289cbfc5feb/href">https://medium.com/media/375e73972f73086057b3c289cbfc5feb/href</a></iframe><p>Of course, as the article’s title tells us, only <em>Partial</em> can really be used in place of <em>any</em>, but all three are in a way linked to each other, so it would be a waste to not to write about them together.</p><p>They offer some quite practical usages. <em>Readonly</em> is very common in typings of React — in components there are some things that you can’t just edit, but you are the person who defines types like a component’s state or properties.</p><p><em>Partial</em> is used wherever you want to offer the possibility to not provide the whole object. A popular usage example is providing the possibility to set the values of an object through one function (or constructor), rather than by setting properties separately. The following listing gives an example of this kind of usage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f1de2e28a1fe6d955328976d273bce6/href">https://medium.com/media/7f1de2e28a1fe6d955328976d273bce6/href</a></iframe><p><em>Required</em> is the opposite of <em>Partial</em>. However, here the usages are not so straightforward, since it’s checking if everything is set just at the types level during compilation. Since I’ve never seen any good, practical usages, I won’t provide any. If you have some, please let me know.</p><h3>Picking and omitting specific a part of a type</h3><p>Earlier we were discussing <em>Partial</em>, which allowed us to make everything in a type optional. That said, we may also want to take a specific part of an object without changing it to be optional (which makes typing even more strict). Let me introduce <em>Pick</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea8488325ea6f573ce0b37546fa7ba4d/href">https://medium.com/media/ea8488325ea6f573ce0b37546fa7ba4d/href</a></iframe><p>Pick works like this: it takes only those specific properties that are in the second type. Here’s an example of how it works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5df7b2d182bfe42e47b0575f3ce60b8c/href">https://medium.com/media/5df7b2d182bfe42e47b0575f3ce60b8c/href</a></iframe><p><em>Pick</em> may not seem very useful, since in fact it only takes the given keys or keys from the second type. So you might ask: why don’t we just use this second type or build a type only from those keys? The reason is this — we keep information about the original type. And why not <em>Partial</em>? The difference is when you turn on <em>strictNullChecks</em> flag in compiler settings. Let’s review an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48b68ede038de9f1120b605f504bcb6d/href">https://medium.com/media/48b68ede038de9f1120b605f504bcb6d/href</a></iframe><p>As you can see, <em>Pick</em> doesn’t allow setting a null value (also undefined) as was defined in the original type. <em>Partial</em> just makes everything nullable, so it does interrupt the original typing. In practice it’s used, for example, in React, in the setState function.</p><p>That said, I’ve mentioned omitting. We don’t have a built-in type for that, but we can build one for ourselves like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5994e705b13733718e56ad423ca75a7/href">https://medium.com/media/a5994e705b13733718e56ad423ca75a7/href</a></iframe><p><em>(UPDATE: </em><a href="https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#typescript-35"><em>Since TypeScript 3.5, we already have built-in Omit type</em></a><em>, so there’s no need to define it by yourself)</em></p><p>In this way, we can perform a following thing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40ec1a90901f9931e501102d9e94f8a9/href">https://medium.com/media/40ec1a90901f9931e501102d9e94f8a9/href</a></iframe><p>If you compare objects e and f from this listing with c and d from listing 7, you can see that we get the complete opposite thing. An example of using <em>Omit</em> can be seen in Ramda to describe the result of a function called <em>omit</em> (quite a surprise, huh?).</p><h3>Unknown and advanced tuple types</h3><p>Both TypeScript features which I describe briefly in this part of the article were introduced in TypeScript 3.0, and I’ve already covered them in <a href="https://itnext.io/typescript-3-0-what-has-come-19f81d1fac60">my article about TypeScript 3.0</a>.</p><p><em>unknown</em> is what should be used when we don’t know a proper type of object. Unlike <em>any</em>,<em> </em>it doesn’t let you do any operations on a value until we know its type (through proper type checks).</p><p>Through advanced tuple types I mean mostly extracting and spreading function arguments with tuple types, which was introduced in TypeScript 3.0. Thanks to them, we can define specific types for specific values in an array. While at first glance it doesn’t sound very helpful, they can be useful in typing functional programming features like compose.</p><p>I encourage you to review the article I’ve linked above for more detailed descriptions, along with usage examples, so you can have a better grasp of them.</p><h3>Summary</h3><p>TypeScript has a lot of typing weaponry ready to be used to keep static types in the dynamically typed environment of JavaScript. The whole problem is that it’s hidden and its usage is not always so straightforward. However, while this article hasn’t described everything that TypeScript offers, I hope it will help you in writing code which will be typed better.</p><blockquote>Post was also published on the <a href="https://www.synergycodes.com/blog/software-development/avoiding-any-in-typescript-advanced-types">blog of Synergy Codes</a> — a software house specializing in process visualization, mapping and modeling.<br>Are you interested in creating data visualization apps? <a href="https://synergycodes.com/gojs-ebook/">Click here to learn about GoJS library</a>!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=691b02ac345a" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/avoiding-any-in-typescript-advanced-types-and-their-usage-691b02ac345a">Avoiding any in TypeScript — advanced types and their usage</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 steps to start increasing quality of your code]]></title>
            <link>https://tomasz-swistak.medium.com/6-steps-to-start-increasing-quality-of-your-code-b063ed6fbae3?source=rss-80cd18546a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/b063ed6fbae3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[project-management]]></category>
            <dc:creator><![CDATA[Tomasz Świstak]]></dc:creator>
            <pubDate>Fri, 30 Nov 2018 08:36:11 GMT</pubDate>
            <atom:updated>2021-06-24T11:27:04.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_VUii6jvQ2aFLBbwkt9yw.jpeg" /></figure><p>Maintaining the high quality of code can be a hard task. When doing a project, everything can happen: time pressure, client’s urgent needs, poor introduction of new developers, lack of code reviews. Generally, every flaw in the development process can leave unwanted code smells in a project. On the other hand, code can be well written in technical terms, while there can still be space to apply some changes which can positively affect a developer’s efficiency.</p><p>We can agree that whenever something bad happens with code, we need to take some countermeasures. Also, it’s great to constantly increase the quality — we are always learning something new that can be nicely used in old code. Here is some advice on how to start with such changes. I’ve already introduced bigger and smaller code improvements in different projects, each with a different history of code smells, and I want to share some thoughts for other developers.</p><h3>1. Identify if a change is necessary</h3><p>Often when we learn about something new, we come across many new ideas which we’d like to use somewhere. Of course, it would be the easiest to apply such changes in a project we’re working on right now. But first, think — do you need it there? Will it make coding easier? What will you, other team members, and the client gain? What’s more, won’t this change be too big? Ask yourself and other developers these questions and see if it’s a good idea.</p><p><strong>Advice:</strong> try to seek only improvements which are known to work well and for which there is a place in the current project. Don’t do anything by force. If you’re not 100% convinced or it’s just an idea which you’ve heard about somewhere — investigate how much work has to be done in your case and how it will affect not only you, but also others as well (developers, management, clients, users…).</p><h3>2. Discuss with others</h3><p>It was hinted at in the previous point, but it’s an important enough issue to warrant its own section. Never decide on your own when there are other people involved in a project. If a change is quick and small, but can make work more comfortable — discuss it with other developers. If the change will take a bigger amount of time and can affect what is already working, your manager should know about it and also be a part of the discussion. Remember that time is money and increasing code quality doesn’t give instantly visible benefits for the business, which brings us to another point…</p><p>But first, <strong>a piece of advice:</strong> remember that every team member should be happy with the change. Don’t force anyone. If someone doesn’t like it, if you weren’t able to convince someone, you should consider once again if it’s a good idea.</p><h3>3. Figure out how this change would generate profit</h3><p>When we work at a software development company, we are a part of a business and we have to generate outcomes. Be it for our bosses or our clients, money is almost always involved. In our (developers’) ideal world, businesspeople should understand that we want to use the most recent frameworks and we need time to develop things in the proper way. In businesses’ ideal world, they care about meeting targets within a given deadline. For example, let’s say the project is a photo gallery working on old ES5 code with jQuery. Most JavaScript developers would like to refactor or rewrite it — write in at least ES2015 and use some popular modern framework like <a href="https://www.synergycodes.com/blog/dependency-injection-in-react-using-inversifyjs">React</a>. But from the business side — what they will gain from it? Remember that it may be understood as a developer’s whim which can only break something, not make anything better. Try to be the salesman — sell your idea by using proper arguments.</p><p><strong>Advice:</strong> non-technical people like to see visual changes. If it’s a change that can be presented in a visually attractive ready sample or can be easily prototyped — do it. If it’s the other kind of change, think about how implementing this can shorten the time for new feature development and try to go this way. Also, it’s vital to be sure that these changes won’t negatively affect what’s already working. Another thing — don’t hide anything. If there’s a possibility that something may go wrong, your management should know about it — after all, it’s their money.</p><h3>4. Plan the changes</h3><p>OK, you’ve discussed the idea with other developers, you’ve sold it to the business, now it’s time to implement it. But remember — if you’re not the only one person working on the code, you need to plan the changes. Again, talk with other team members. If you want to do as many changes as possible at once, ask others if they aren’t planning to work on the same parts of the code in order to avoid unpleasant merge conflicts. If the changes are big, plan with others how to make them incrementally, so you won’t fix their new code. Even more, let them help you, they also can make similar changes at the same time or at least write code that will be compatible with the new approach.</p><p><strong>Advice:</strong> it can be a bit annoying, but always let others know about every major change you make. When you start development, synchronize frequently with others.</p><h3>5. Improve</h3><p>So, when everything’s ready and steady, it’s time to go. Make the improvements you’ve discussed according to the set plan — don’t do anything more or in a different way. Seek advice from developers who’ve already done it. This may sound a bit like motivational mumbo-jumbo, but even when you don’t succeed, you haven’t wasted time. You and the other team members have learned something new, and that’s important.</p><p>And <strong>our advice here</strong> could be the same as for the previous point: synchronize with others. Don’t be that guy who stays quiet for a few days and later sends a pull request with over 100 files changed. I did something like this and my colleagues’ reactions keep haunting me at night (all right, it isn’t so dramatic, but it certainly wasn’t the wisest thing I’ve done).</p><h3>6. Don’t repeat mistakes</h3><p>Also remember that after implementing the changes, it’s vital to make sure that the things which went wrong won’t happen again. You can’t continuously improve the same thing. Teach others, and keep on guard yourself. If there was a faulty process — maybe you should talk with management about it? Bad code can be seen as a sickness, and improving code quality in many cases is just a fight with the symptoms. The most important thing is to find the real causes of the problem and do something about them.</p><h3>To sum up…</h3><p>Improving code quality is not only a technical process. If there’s money involved, it’s also a business process. Never make it a secret, always inform everyone involved about all the changes. Also, it shouldn’t be just code improvement. Primarily, it should be improvement of your skills and development processes so something like that doesn’t happen again.</p><p><em>Post was also published on </em><a href="https://www.synergycodes.com/blog/6-steps-to-start-increasing-quality-of-your-code"><em>Synergy Codes’ blog</em></a><em> </em>— a company developing data flow diagram applications and web applications.</p><p><strong>Are you interested in creating data visualization apps? </strong><a href="https://synergycodes.com/gojs-ebook/"><strong>Click here to learn about GoJS library</strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b063ed6fbae3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency injection in React using InversifyJS]]></title>
            <link>https://itnext.io/dependency-injection-in-react-using-inversifyjs-a38ff0c6601?source=rss-80cd18546a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/a38ff0c6601</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Tomasz Świstak]]></dc:creator>
            <pubDate>Mon, 03 Sep 2018 07:31:55 GMT</pubDate>
            <atom:updated>2021-06-24T11:21:39.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITU04s0BnNmGtAsbX9iCtQ.jpeg" /></figure><p>InversifyJS is a powerful, lightweight and easy-to-use library for dependency injection in JavaScript. Unfortunately, due to the nature of React, using it as a component feature is not straightforward. This is because dependency injection in InversifyJS relies on a constructor injection, while React doesn’t want users to extend constructors of its components.</p><p>However, there are methods which allow us to use inversion of control in our React code. By creating an example project, I will show you how to bypass this issue when working on projects.</p><h3>Example project</h3><p>I’ve created a simple React project in TypeScript for this article. The interesting points here are:</p><ul><li>IoC initialization</li><li><em>NameProvider</em> class (which will provide a name to be displayed by the React component)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f31386ec94d2239a9b0662d07f0a06b0/href">https://medium.com/media/f31386ec94d2239a9b0662d07f0a06b0/href</a></iframe><p>It’s a typical usage of InversifyJS, creating a new IoC container to which we bind a class under a given identifier (in this case a <em>string</em>, but it can also be a <em>Symbol</em> or a type). This is a transient scope declaration, which means that for every injection, it will create a new instance of the class. There are also singleton scope (always the same instance for every injection) and request scope (the same instance for one call of <em>container.get</em>).</p><p>Every class which can be injected through Inversify has to be decorated with <em>injectable</em>, usually by using an inject decorator inside the constructor or on properties. However, this is not possible with React, so we have to do it differently.</p><p>The rest of the project is a simple React app. <em>Hello</em> is a component that uses a provider to display a name in a header. In the <em>index</em> we are rendering it in DOM. The code won’t work until we inject our <em>NameProvider </em>instance.</p><h3>Using inversify-inject-decorators</h3><p><a href="https://www.npmjs.com/package/inversify-inject-decorators">inversify-inject-decorators</a></p><p>This is the recommended way of using Inversify when we can’t do a constructor injection. The library provides four additional decorators to use in projects: <em>lazyInject</em>, <em>lazyInjectNamed</em>, <em>lazyInjectTagged</em>, <em>lazyMultiInject</em>. As the name suggests, they provide a lazily evaluated injection, which means the dependency isn’t provided, as is normal, while the object is initialized. Instead it is provided during its first usage and is then cached for later. Caching can be turned off by providing a proper Boolean value during initialization.</p><p>To do this, we first execute the <em>getDecorators</em> function, which will return the decorators mentioned above. In this case, we will only use <em>lazyInject</em>, since we don’t use names or tags and we don’t bind multiple classes under one identifier to use multi-injection. We then just decorate our <em>nameProvider</em> property with <em>lazyInject</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4464bd7d74e40b06c8c94e73db465c0a/href">https://medium.com/media/4464bd7d74e40b06c8c94e73db465c0a/href</a></iframe><p>It’s fairly simple to use in most React and InversifyJS projects. Unfortunately, it’s quite common to get circular dependencies using this method, especially while having container modules in separate files and later combining them into one container, in something similar to an ioc.ts file. This can be avoided by dividing module loading and exporting <em>lazyInject</em> into separate files. You can see the whole example here:</p><p><a href="https://github.com/tswistak/react-inversify-inject-decorators-example">tswistak/react-inversify-inject-decorators-example</a></p><h3>Using inversify-react</h3><p><a href="https://www.npmjs.com/package/inversify-react">inversify-react</a></p><p>inversify-react is a library which carries out dependency injection in a slightly different way. For our usage, we get a React component <em>Provider</em> which holds the IoC container and passes it down the React tree. We also get four decorators — <em>provide</em>, <em>provide.singleton</em>, <em>provide.transient</em> and <em>resolve</em>. In our example, we will need only resolve to get the dependency and <em>Provider</em> to pass it to the container. <em>resolve</em> works in a similar way to <em>lazyInject</em> in the previous method, but it doesn’t require any initialization.</p><p>To use it, we simply put our app inside the <em>Provider</em> component to which we are passing the IoC container. In <em>Hello</em>, we then decorate <em>nameProvider</em> with <em>resolve</em> and provide it with a proper identifier. ioc.ts should remain unchanged (in contrast to the previous method). You can check all changes here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a29f2f2b022ef6a1a969c99876d99d0/href">https://medium.com/media/4a29f2f2b022ef6a1a969c99876d99d0/href</a></iframe><p>This easy method means we don’t need any changes within IoC, we are just passing a container down the React tree and getting dependencies using a proper decorator. However, the library is currently in the early stage of development and the API may even change at any time without warning. Another downside is the fact that we only get the simplest case of dependency injection. It will cover most cases, but I’ve needed multi-injection in some projects, which I could not do with this library. You can see the whole example here:</p><p><a href="https://github.com/tswistak/inversify-react-example">tswistak/inversify-react-example</a></p><h3>Using react-inversify</h3><p><a href="https://www.npmjs.com/package/react-inversify">react-inversify</a></p><p>The name is similar to the previous library, but this one has an entirely different approach. We have both a <em>Provider</em> component, which is similar to that in inversify-react, and a higher order <em>connect</em> component, which injects dependencies to props.</p><p>It is trickier to use than previous methods as we don’t use decorators inside components. We need to create a class where we inject dependencies in a typical way, using <em>inject</em>. We then use <em>connect</em> HOC to provide an instance of this class to the properties of our component, as such:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e9a33d5332caeaf87748753a80a0274/href">https://medium.com/media/4e9a33d5332caeaf87748753a80a0274/href</a></iframe><p>Usage is a bit more complicated, as we need to create an additional class and wrap our component with HOC. In the example, I’ve used it as a decorator but you can also use it in a traditional way. Generally, this method is most in line with React, since objects are passed as properties, not instantiated inside the component. Another advantage is the full usage of InversifyJS, meaning we don’t need to depend on what the library offers — but it does involve writing a lot more code than other solutions. You can see the whole example here:</p><p><a href="https://github.com/tswistak/react-inversify-example">tswistak/react-inversify-example</a></p><h3>Summary</h3><p>We therefore have three ways of using InversifyJS in React projects. Each has advantages and disadvantages, meaning that there is no perfect solution, but I hope this makes it a little easier for you to choose the library that best suits your project.</p><p><em>Post was also published on </em><a href="https://www.synergycodes.com/blog/dependency-injection-in-react-using-inversifyjs"><em>Synergy Codes’ blog</em></a><em>.</em></p><p>Are you interested in creating data visualization apps? <a href="https://synergycodes.com/gojs-ebook/">Click here to learn about GoJS library</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a38ff0c6601" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/dependency-injection-in-react-using-inversifyjs-a38ff0c6601">Dependency injection in React using InversifyJS</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript 3.0 - what has come?]]></title>
            <link>https://itnext.io/typescript-3-0-what-has-come-19f81d1fac60?source=rss-80cd18546a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/19f81d1fac60</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tomasz Świstak]]></dc:creator>
            <pubDate>Tue, 31 Jul 2018 09:12:40 GMT</pubDate>
            <atom:updated>2021-06-24T11:20:59.948Z</atom:updated>
            <content:encoded><![CDATA[<h3>TypeScript 3.0 — what has come?</h3><p>Nearly two years after the release of TypeScript 2.0 and two months from the latest version 2.9, Microsoft has released the newest version of TypeScript. Let’s see what changes have been made and how they can affect our daily work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzf8w-N-QK7iq8pwv4UPBw.jpeg" /></figure><p>In TypeScript 3.0 we can identify just five changes affecting the way you can use the language. Only one of those is flagged as a breaking change. But that’s enough introduction, let’s see what’s new!</p><h3>Richer tuple types</h3><p>Tuples in TypeScript are in fact JavaScript strongly-typed arrays (at the single element level) with constant length. At least, that’s the way it used to be, and you can see an example in Listing 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c69d366a1ae79175e442fdebbd392583/href">https://medium.com/media/c69d366a1ae79175e442fdebbd392583/href</a></iframe><p>Starting from TypeScript 3.0 we can define tuples with an undefined maximal number of elements, needing just a minimum. An example is given in Listing 2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f207d66ae7a593280f306dd93a7738ad/href">https://medium.com/media/f207d66ae7a593280f306dd93a7738ad/href</a></iframe><p>The first element has a string type, which is mandatory, but the rest, which is just numbers, can be omitted. What’s more, we can even define the tuple without a lower limit (in fact it’s just an array) or an empty tuple. See Listing 3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24a970c7043af8cfb63e245d3656ad82/href">https://medium.com/media/24a970c7043af8cfb63e245d3656ad82/href</a></iframe><p>Such tuples have practical uses. For example, we can force an array to have at least one element on the types level. Another use, in a more complex context is shown in the next part of the article.</p><h3>Extracting and spreading function arguments with tuple types</h3><p>As you may know, in JavaScript we can use arguments provided to the function, even when we haven’t named any in the code, by using the <em>arguments</em> variable. Of course, this isn’t allowed in TypeScript (with default configuration), where we have to tell the compiler everything. The difference is shown in Listing 4.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01f3ca0b4fccabce454559fc1812028c/href">https://medium.com/media/01f3ca0b4fccabce454559fc1812028c/href</a></iframe><p>This is fine for the compiler, but when we’re using TypeScript, we don’t want to use the <em>any</em> type. Let’s say we want to have only strings and numbers provided. Then, we can of course change <em>any</em> to <em>(string | number)</em>. But, this way we are telling thecompiler “I want to have an array which has strings or numbers”. We don’t restrict which element is a string, which is a number, and how many we should have. Let’s say we know that the first argument is a string, the following two are numbers and the rest are strings. From TypeScript 3.0 we can define it using tuple types as shown in Listing 5.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8571945cec643e946d610578a8ef32cd/href">https://medium.com/media/8571945cec643e946d610578a8ef32cd/href</a></iframe><p>How about a different use case? Let’s see Listing 6.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94ffd85f27ac4d3a20a692b881f338ec/href">https://medium.com/media/94ffd85f27ac4d3a20a692b881f338ec/href</a></iframe><p>TypeScript 3.0 allows us to do a generic type <em>T1 extends any[]</em> which in fact creates a tuple type. Here we tell the compiler that <em>T1</em> is the type of all of the first function’s arguments. It can be anything, but we will have it strongly typed. As you can see in the last line of listing 6, strict type checking works and tells us, that we can’t use a string in place of a number. This example shows, that we will be able to use such typings in functional programming. Maybe we will better typings for libraries like Ramda in the future?</p><h3>“unknown”</h3><p>As you may know, TypeScript has an <em>any</em> type which can handle literally everything — it reverts JavaScript’s weak typing for the specific variable. It’s a bad practice to overuse it, but due to JavaScript’s nature sometimes we need it. One case, we want to use <em>any</em> is when we don’t know the type, but we will check what it is and later use it strongly typed. With <em>any</em> we wouldn’t even need to check the type — we could use a variable just like that without compiler errors. From TypeScript 3.0 we can use the <em>unknown</em> type. It tells the compiler “We don’t know what we have here, so we can’t use it until we know what it is”. The difference is shown in Listing 7.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/251cfe7fbf4166cf2faa29e5368913c5/href">https://medium.com/media/251cfe7fbf4166cf2faa29e5368913c5/href</a></iframe><p>It’s worth noting that this is a breaking change, because from version 3.0 <em>unknown</em> has become a language’s keyword, so it can’t be used as a name anymore.</p><h3>Support for defaultProps</h3><p>Another novelty in TypeScript 3.0 is language-level support for React’s <em>defaultProps</em>. For those of you who haven’t heard of <em>defaultProps</em>, I’ll describe them briefly. Normally, in JavaScript (ECMAScript 6), if we would like to provide the default React component’s parameters, we would do it using static object <em>defaultProps</em> as shown in Listing 8.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e57d66c8288ee91f533e234c822bf643/href">https://medium.com/media/e57d66c8288ee91f533e234c822bf643/href</a></iframe><p>As we can see, thanks to the usage of defaultProps we don’t need to perform null checks on title, because we are sure that it always has some value. In the past, TypeScript couldn’t understand this and we had to do a null check. In Listings 9 and 10 I’ve shown how we could approach this issue in TypeScript 2.x, and how we can do it now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/295bb440a8d55ab4ed1c7e7e9ba52304/href">https://medium.com/media/295bb440a8d55ab4ed1c7e7e9ba52304/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf17bff10d102bcd575f63c958c7e03c/href">https://medium.com/media/cf17bff10d102bcd575f63c958c7e03c/href</a></iframe><p>As you can see, the code from the newest TypeScript version doesn’t need the null check, because the compiler can see the parameter value defined in <em>defaultProps</em>.</p><h3>Project references</h3><p>Probably the biggest new feature of TypeScript 3.0. From now on, we will be able to define cross‑project references. Thanks to this change, we will be able to use some new project architecture scenarios like:</p><p>· Using shared code for client and server projects. Compiled output would also share the code, not have a separate copy of each shared code file.</p><p>· Unit tests which don’t contain own copy of the main project’s files.</p><p>· Monorepos (many projects dependent on each other), along with the use of battle-tested solutions like Lerna and Yarn Workspaces</p><p>That’s all thanks to new entries in tsconfig: <em>composite</em> flag for compiler options and <em>references</em>. Also, we have a new parameter for tsc (TypeScript’s compiler): — build which can build whole TypeScript project’sin accordance with a given tsconfig.</p><p>As an example, let’s consider the following project structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*V2spFhyFUpiNkN_TiPf8gg.png" /></figure><p>The client’s project <em>tsconfig.json</em> is provided in Listing 11. It can be built using the command: <em>tsc -b composite/client</em>. To use a shared project we simply imported the things we need from it without any additional structures in the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8865d4488eebded1d862fe8e6a5787c/href">https://medium.com/media/a8865d4488eebded1d862fe8e6a5787c/href</a></iframe><p>After compiling both client and server we get the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/1*4nYCrOE_btwQZU2Ce2CKpg.png" /></figure><p>As you can see, the “shared” directory is in fact shared between the client and the server. In older versions, we would get the “shared” directory copied to both client and server, thus creating the output structure different from the source structure.</p><p>For information on how to use project references with Lerna, I recommend this GitHub repository: <a href="https://github.com/RyanCavanaugh/learn-a">https://github.com/RyanCavanaugh/learn-a</a>.</p><h3>Concluding…</h3><p>As we have seen, there weren’t a lot of changes. Mostly they concerned a typing system to provide static types for many more JavaScript cases. The biggest change is, of course, project references. However, for now, we can’t tell how widely it will be used. I’m eager to see how much value it will provide to my new and existing projects and how it will affect other projects.</p><p>Post has also been published on <a href="http://www.synergycodes.com/blog/typescript-3-what-has-come">Synergy Codes’ blog</a>.</p><p>Are you interested in creating data visualization apps? <a href="https://synergycodes.com/gojs-ebook/">Click here to learn about GoJS library</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19f81d1fac60" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/typescript-3-0-what-has-come-19f81d1fac60">TypeScript 3.0 - what has come?</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating simple application with GoJS, part 3]]></title>
            <link>https://itnext.io/creating-simple-application-with-gojs-part-3-9bfc8aa8813b?source=rss-80cd18546a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bfc8aa8813b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Tomasz Świstak]]></dc:creator>
            <pubDate>Mon, 18 Jun 2018 09:56:15 GMT</pubDate>
            <atom:updated>2021-06-24T11:19:21.059Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I’ve explained how to create a GoJS diagram, as well as how to set and style edges. In order to make the diagram fully interactive, we still need to give the option of inserting elements. To do this, we’ll create a palette built into GoJS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzSv_Azryh3zRiEEwJrD7A.jpeg" /></figure><blockquote>Post written in cooperation with <a href="http://www.synergycodes.com/">Synergy Codes</a>.</blockquote><p>For the first time at the series? Check out previous parts!</p><ul><li><a href="https://itnext.io/creating-simple-application-with-gojs-part-1-e3c320765def">Part 1 — diagramming basics</a></li><li><a href="https://itnext.io/creating-simple-application-with-gojs-part-2-c33139e934ba">Part 2 — setting node edges</a></li></ul><h3>Palette</h3><p>A palette is a separate canvas that displays all the nodes defined in it and allows you to transfer them to the main diagram. It is configured in a manner analogical to the diagram, but through the creation of a <strong>go.Palette</strong> object. However, in order to do this, we should first add an additional <strong>div</strong> to the HTML file where the palette will be contained. We can also add a function to initialize the palette in the JS file, which we will also make available outside (<strong>initPalette</strong>). In our example, we’ll put the palette next to the diagram. Here’s how we will edit the HTML file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ea7fa0697766f41798e6ad2808002d0/href">https://medium.com/media/8ea7fa0697766f41798e6ad2808002d0/href</a></iframe><p>The next step is to complete the initPalette function we’ve created. As I mentioned earlier, initialization of the palette isn’t very different from initialization of the diagram. Here we will use our getTemplates() function for the second time — when we do this, we don’t have to define the appearance of the shapes again, just for the palette. However, it should be stressed that we can create still other appearances for shapes — when moving to the diagram, what’s important is the element’s category, not its appearance. In addition, to enable transfer from the palette to the diagram, we need to add the allowDrop field to the diagram initialization and set its value to true. Here’s what the code should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aee310054800d6344cf454d503414600/href">https://medium.com/media/aee310054800d6344cf454d503414600/href</a></iframe><p>Now here’s what the application will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*atuBeOYTUgljSWTuUy2N-g.png" /><figcaption>Figure 1. Diagram with added palette</figcaption></figure><h3>Final touches — adding the grid</h3><p>At the end, in order to improve the appearance of the application, let’s add two more things: a grid the elements will be snapped to, and their auto-positioning.</p><p>Let’s start with the grid. You’ll find it under <strong>diagram.grid</strong>, and the only thing we have to do is change its visible property to <strong>true</strong>. In order to add dragging, it has to be configured in the built-in drag tool available under <strong>diagram.toolManager.draggingTool</strong>. We can use two properties here: <strong>isGridSnapEnabled</strong> to enable dragging and <strong>gridSnapCellSize</strong> to define the size of the grid (for our example let’s define a size of 50x50). If we’re using node size modification (resizingTool), we would set analogous fields in it as well. Here’s the code that will be responsible for setting the grid:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f7834fd414f577c250170fbcc4ed06b/href">https://medium.com/media/6f7834fd414f577c250170fbcc4ed06b/href</a></iframe><h3>Final touches — nodes positioning</h3><p>The easiest way to position the elements is by changing the layout of the diagram. The default layout does not define any automatic arrangement of elements — it only arranges them so that they don’t overlap each other. However, this is offered by other layouts: <strong>GridLayout</strong> (placement on the grid), <strong>TreeLayout</strong> (tree), <strong>ForceDirectedLayout</strong> (graphs pushing the elements away from each other), <strong>LayeredDigraphLayout</strong> (graph arranged in columns and rows) and <strong>CircularLayout</strong> (arrangement of nodes on a circle).</p><p>We set the layout as another field during initialization of the diagram — a layout we pass a new instance of the selected layout to, along with its possible configuration. Here’s an example of how we can implement it for <strong>LayeredDigraphLayout</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34f88c621ff3c43fc415c1be75b4b99a/href">https://medium.com/media/34f88c621ff3c43fc415c1be75b4b99a/href</a></iframe><p>The effect is presented below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*dWFa-wdNKQ-h_0t6kCgzbQ.png" /><figcaption>Figure 2. Diagram with enabled grid and set LayeredDigraphLayout</figcaption></figure><p>You can also check out other available layouts, but you need to keep their limitations in mind. For example, <strong>TreeLayout</strong> won’t be able to handle a situation where two edges lead to one node.</p><p>Results of the whole tutorial you can check on the <a href="https://github.com/tswistak/diagram-example-gojs">GitHub repository</a> or on Codepen:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftswistak%2Fembed%2Fpreview%2FwjZqbO%3Fheight%3D600%26slug-hash%3DwjZqbO%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftswistak%2Fpen%2FwjZqbO&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1194144.wjZqbO.small.0f64701a-18ca-4498-8454-5e0768a5b6a3.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e173f03783f661ec44f46cf36ae31892/href">https://medium.com/media/e173f03783f661ec44f46cf36ae31892/href</a></iframe><h3>Summary</h3><p>As you’ve definitely understood reading this article, we have developed an advanced application without a lot of work, using just the functionality of the GoJS library without additional hacking. There’s a total of around 120 lines of JavaScript code, which shows clearly that we haven’t done anything difficult. GoJS allows us to save a lot of time that we would otherwise spend on creating a palette, handling elements on the canvas, or other nontrivial things like automatic positioning of elements. This library also offers other advantages, such as transparent documentation, lots of ready examples, and very good support from the producer. TypeScript users will be also satisfied because official typings are made available, as well as free extensions of the library written in TypeScript.</p><p>As much as we’d like to, it was impossible to present all the capabilities of the library in this series of articles. I strongly encourage you to go through the examples available on <a href="https://gojs.net/">the developer’s website</a>.</p><p>Post is also published on <a href="http://www.synergycodes.com/blog/">Synergy Codes’ blog</a>, you can check it out <a href="http://www.synergycodes.com/blog/simple-gojs-application-finishing-touches">here</a>.</p><p>Would you like to learn more about GoJS? <a href="https://synergycodes.com/gojs-ebook/">You can download the free ebook here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bfc8aa8813b" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/creating-simple-application-with-gojs-part-3-9bfc8aa8813b">Creating simple application with GoJS, part 3</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating simple application with GoJS, part 2]]></title>
            <link>https://itnext.io/creating-simple-application-with-gojs-part-2-c33139e934ba?source=rss-80cd18546a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/c33139e934ba</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tomasz Świstak]]></dc:creator>
            <pubDate>Wed, 13 Jun 2018 10:43:47 GMT</pubDate>
            <atom:updated>2021-06-24T11:18:58.740Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last post I showed you how to get started with a GoJS application. I explained how to create a diagram and how to present data using it. Let’s go another step further and set up edges in a proper way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*KOn10YqYuGsceop4LBlxzg.jpeg" /></figure><blockquote>Post written in cooperation with <a href="http://www.synergycodes.com/">Synergy Codes</a>.</blockquote><p>Looking for the first part? Check it on <a href="https://itnext.io/creating-simple-application-with-gojs-part-1-e3c320765def">ITNEXT</a>.</p><h3><strong>Ports</strong></h3><p>While our diagram is starting to look better, there are a few issues that stick out. First — it can’t be edited (the only thing you can do is move the nodes around and clone them using the CTRL key), and second — we might want the edges to be drawn between specific points of the nodes. This is particularly visible in the objects that were created from the SVG paths — the best thing would be to set the entry from the left and set the exit from the right. But to do this, we first need to define the ports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*6QvZkFkLKl-ZExn9XXnwXw.png" /><figcaption>Figure 1. What we have after completing the first part of this tutorial</figcaption></figure><p>Ports are parts of nodes with only one function — setting the edges in relation to the rest of the object. They may consist of elements of nodes that already exist (even an entire node), or they can be new elements created specially for this purpose. Ports are defined by setting a value for the <strong>portId</strong> field. There are some other things we can do, for example: define whether we can create new links from the port (<strong>fromLinkable</strong> field) and whether we can attach new links to it (<strong>toLinkable</strong>). For the purposes of this example, the ports will be defined as visible shapes, but they can be any objects (including invisible ones).</p><h3>Setting ports for node templates</h3><p>In the case of the first node template (black circle) , we want to put the port right in the middle. In order to make it clear that this is where the edges go, we will change the color of the circle and set a fixed size for it. We’ll also configure it to make it possible to create connections from this port in both directions. Here’s how we’ll define the shape in this case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c807c10ed4c42c402845d7fb5f55668/href">https://medium.com/media/8c807c10ed4c42c402845d7fb5f55668/href</a></iframe><p>Like I already mentioned, it’s important for the <strong>portId</strong> field to have a set value. However, this value can be an empty string. If we assign an empty string, this port will be the default port.</p><p>For the second node template (SVG path), we want to define the port on its left and right side. This can be done in two ways: by changing the arrangement of elements to Horizontal and setting the shapes in the order of port-main shape-port, or by changing to Spot, then setting the ports to the Left and Right positions with the main shape in Center. The second way is more flexible, so it’s the one we will use. On the left side, we will insert the same rectangle as on the first shape and setting it so that you can only link to it. On the right side, we will insert a rectangle from which we can only lead the edges. In order to distinguish them, we should give them different identifiers than an empty string (e.g., entry and exit). Here’s what this definition looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cd8aeaf2303e36f06a1885658e4bd63/href">https://medium.com/media/8cd8aeaf2303e36f06a1885658e4bd63/href</a></iframe><p>For the third template (two rectangles), let’s modify only the square on the top. We’ll make it a port by adding a <strong>portId</strong> with an empty string, and we’ll set <strong>fromLinkable</strong> and <strong>toLinkable</strong> to <strong>true</strong>. After creating the ports, here’s what the diagram should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*52TwNNFDeu548tTScdS5Mg.png" /><figcaption>Figure 2. Diagram with preliminary configuration of the ports</figcaption></figure><h3>Setting links to use ports</h3><p>As the figure above shows us, the ports work perfectly in the case of the first and third category, but they don’t work for the second one. The same thing happens when it comes to drawing links. Drawing between the first and third category is no problem, but with the second category the edges jump out of the ports. There are two reasons why this happens. First, we haven’t defined in the link model which ports the connections should occur between. Second, we haven’t set in the model how to store connections between ports. So let’s go back to <strong>initDiagram</strong> and the definition of the model. We need to add two fields to <strong>GraphLinksModel</strong>: <strong>linkFromPortIdProperty</strong> and <strong>linkToPortIdProperty</strong>. These determine how we define the ports used in the model. Additionally, we should define in <strong>linkDataArray</strong> how the edges for nodes 2 and 3 (those belonging to the second category) will be done. Here’s what these changes should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17884a8d5dff392c4314a0576886e2d5/href">https://medium.com/media/17884a8d5dff392c4314a0576886e2d5/href</a></iframe><p>Now here’s what the edges on the diagram should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*ZaULlugaa4ac3olRdpTS8A.png" /><figcaption>Figure 3. Diagram after proper configuration of the ports</figcaption></figure><p>In the next part we’ll put the finishing touches on this diagram. As for the current part, you can check out the result here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftswistak%2Fembed%2Fpreview%2Fyjrory%3Fheight%3D600%26slug-hash%3Dyjrory%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftswistak%2Fpen%2Fyjrory&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1194144.yjrory.small.581e99d3-3322-4742-9075-1adf170637b2.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/41d377c8c84b23bf5b648e2e3c0c165f/href">https://medium.com/media/41d377c8c84b23bf5b648e2e3c0c165f/href</a></iframe><p>Want more? Check out the <a href="https://itnext.io/creating-simple-application-with-gojs-part-3-9bfc8aa8813b">third part of this tutorial</a>!</p><p>Post is also published on <a href="http://www.synergycodes.com/blog/">Synergy Codes’ blog</a>, you can check it out <a href="http://www.synergycodes.com/blog/simple-gojs-application-setting-and-editing-edges">here</a>.</p><p>Would you like to learn more about GoJS? <a href="https://synergycodes.com/gojs-ebook/">You can download the free ebook here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c33139e934ba" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/creating-simple-application-with-gojs-part-2-c33139e934ba">Creating simple application with GoJS, part 2</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating simple application with GoJS, part 1]]></title>
            <link>https://itnext.io/creating-simple-application-with-gojs-part-1-e3c320765def?source=rss-80cd18546a46------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3c320765def</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tomasz Świstak]]></dc:creator>
            <pubDate>Mon, 04 Jun 2018 10:11:32 GMT</pubDate>
            <atom:updated>2021-06-24T11:18:11.305Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating simple application with GoJS — part 1</h3><p>In this article, I will present the basic capabilities of GoJS by creating an application with very simple code. It will be designed for drawing uncomplicated diagrams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDCr0aJ8k_nJtSKTCmNwCQ.png" /></figure><blockquote>Post written in cooperation with <a href="http://www.synergycodes.com/">Synergy Codes</a>.</blockquote><h3>Start with the library</h3><p>GoJS is a JavaScript library that takes complex data and runs it through flexible modeling options to create visualizations that are easy to understand and put into action. You can read more about GoJS on <a href="https://gojs.net/latest/index.html">official website</a> or in <a href="http://www.synergycodes.com/blog/gojs-easy-data-visualization">Synergy Codes’ blog post</a> about it.</p><p>The starting point for us is the HTML file where we import the library. We can download it directly from <a href="https://gojs.net/latest/doc/download.html">the website</a>, from the npm, or we can use the CDN. The next step is to add the <strong>div</strong> element — the future location of the diagram. NOTE: We don’t create the canvas ourselves, as the library does it for us. However, the div itself may be freely refined to make it match the website. The file should look more or less like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e093bb41acb24a83aaf6f2fac56292a7/href">https://medium.com/media/e093bb41acb24a83aaf6f2fac56292a7/href</a></iframe><h3>Code structure</h3><p>The next step is to write JavaScript code that creates the diagram. We create a diagram.js file where we will put the entire logic of the application. We can create it in any convention — GoJS doesn’t dictate any specific way of building sources. For the purposes of this example, I will create an IIFE (Immediately Invoked Function Expression), which will be a named diagram with the <strong>initDiagram</strong> function available externally. By using IIFE, we will be able to hide a part of our implementation from outside access.</p><p>In the case of GoJS, our starting point for creating all objects is the <strong>go.GraphObject.make</strong> function, which calls the factory method of the selected class. It’s used so often that we should assign it to a variable with a shorter name. The generally accepted convention is to use the dollar sign for this reason. However, we need to be careful in the case of parallel use of jQuery. As the first argument, this function accepts the class whose instance is supposed to be created, while the values of individual fields of the object are accepted as subsequent arguments. It’s worth emphasizing that usually the string is given as a second argument with the value of one selected field defined in the object. Generally, it’s the field whose value is most important in the given context, such as the type of created figure.</p><h3>Creating a GoJS diagram — preparation</h3><p>The first thing that we want to create is the diagram itself. It is located under the <strong>go.Diagram</strong> class. The most important parameter is the <strong>id</strong> of the element it’s supposed to be placed in. This is why we call it $(go.Diagram, ‘diagram-content’).</p><p>In order to better specify the operation of the diagram object, check what fields it has in the documentation. For instance, we may assign the value <strong>go.Spot.Center</strong> to the field <strong>initialContentAlignment</strong>. This initially places the diagram’s elements at its center (by default they are in the upper left corner) of the application. Let’s put it into the <strong>initDiagram</strong>. We have to remember to call this function in the HTML file. We should get the following JS and HTML files:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7b22ace555bfa5986e53070bf32900d/href">https://medium.com/media/e7b22ace555bfa5986e53070bf32900d/href</a></iframe><p>The diagram is empty, so unfortunately we won’t see any action yet. The only thing that will show us that GoJS is working is the default action lock of clicking the right mouse button on the diagram.</p><h3>Presentation of data on the diagram</h3><p>The basis for the diagram is the creation of a data model for it to operate on. The model consists of two tables — <strong>nodeDataArray</strong> (data of nodes) and <strong>linkDataArray</strong> (data of edges). Nodes are the main elements of a diagram that graphically represent the objects (for example, an entity in a diagram of relations of entities). Links (edges) are the connections between nodes (directed or not), which, depending on the type of diagram, may have different meanings (such as the relation between entities in an ERD diagram).</p><p>We define the individual nodes as objects where the only required field is key, for example, a unique identifier. In addition, we can optionally define the category of objects, as well as complete them with any data which will be stored along with the node in the diagram. Edges are also defined as objects having two required fields — <strong>from</strong> and <strong>to</strong>, whose values determine which nodes are connected. Like in the case of nodes, we may also add our own additional data.</p><p>The diagram model is located under the model field of the diagram object. It’s best to define it by creating a <strong>go.GraphLinksModel</strong> object we pass the nodes and edges to. Here’s an example of what a model definition might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5567c25be0ebbbd31b55edf43a9c3d26/href">https://medium.com/media/5567c25be0ebbbd31b55edf43a9c3d26/href</a></iframe><p>After placing it in the <strong>initDiagram </strong>and running it, we should get a very simple diagram. It will show us the values entered in key fields connected by edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*HFkJBVRVuDyRM_P_oMcOBQ.png" /><figcaption>Figure 1. First diagram</figcaption></figure><p>The next step is to provide the objects with an appearance. The appearance is set by creating a <strong>go.Node</strong> object in which we subsequently create objects defining the shape (<strong>go.Shape</strong>). The simplest definition of the object’s appearance (template) would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a95fff21d19a5e96674ed96bd365a5d/href">https://medium.com/media/0a95fff21d19a5e96674ed96bd365a5d/href</a></iframe><p>In this case, we will create a black circle to represent the object. <strong>Auto</strong> means the arrangement of individual shapes. In the case of <strong>Auto</strong>, each shape defined inside go.Node will be placed in layers at the center of the object. In the case of shapes, <strong>Circle</strong> was selected here, but there are many others available at: <a href="https://gojs.net/latest/samples/shapes.html">https://gojs.net/latest/samples/shapes.html</a>. We could also set field values in the shape object — this would let us specify elements like: <strong>fill</strong>, <strong>stroke</strong> or <strong>size</strong>. In addition, we can load these values from the data model using <strong>go.Binding</strong>.</p><p>Another way to define the appearance is to create a shape using the SVG path definition. Then, we use this path as the value of the <strong>geometryString</strong> field. Here’s an example of what the template definition would look like in such a case (we’ll also set the size and color of the fill):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e17288fda24e5bd476bbdea50a03921/href">https://medium.com/media/5e17288fda24e5bd476bbdea50a03921/href</a></iframe><p>It’s also possible to define the appearance using images in any format (including SVG). In such cases, instead of <strong>go.Shape</strong> we have to use <strong>go.Picture</strong>. Interestingly, <strong>go.Picture</strong> can store not only images, but also other canvas-type elements. This allows us to create even more advanced visualizations.</p><p>Another way of defining the appearance of objects is to combine many different shapes into one. The advantage of this approach is that after dividing the object into several smaller ones, we can define different behaviors for each part (for example, one of the shapes may be a button on which we define a click action — in this case, only this fragment will have this event assigned). In order to create complex objects, it’s worth learning about methods for arranging shapes on an object. We’ve used <strong>Auto</strong>, which means placing everything in the middle. We also have other options, the most basic of which include: <strong>Horizontal</strong> (from left to right), <strong>Vertical</strong> (from top to bottom), <strong>Spot</strong> (placement on predetermined positions like <strong>Center</strong>, <strong>Top</strong>, <strong>Bottom</strong>, etc.). Subsequent shapes are passed as the next arguments of the function creating the Node, and they are placed in this order. For example, two rectangles, each with a different appearance and placed one on top of the other, would be defined in like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bad0d52ab90ca83202ff7883892d5efb/href">https://medium.com/media/bad0d52ab90ca83202ff7883892d5efb/href</a></iframe><p>However, what if we want different types of objects? To do this, instead of assigning the appearance to <strong>nodeTemplate</strong>, we complete the map — <strong>nodeTemplateMap</strong>, where the key is the category of the object (<strong>category</strong>, which we have defined in the model), while <strong>template</strong> is the value. For the purposes of this example, let’s assume that we’ll use the definitions given above for the categories: <strong>first</strong> will be a circle, <strong>second</strong> will be SVG shape, <strong>third</strong> will be two rectangles. However, for practical reasons, we shouldn’t assign template directly to the map, but rather create the function that will return the template we will assign to which category, and then supplement the map — nodeTemplateMap using the data from it. Note that this map should be completed before we supply the diagram with the model. For example, it could look like this (some fragments of the code have been left out for clarity):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37aabffecaad25dfe96675abef41829b/href">https://medium.com/media/37aabffecaad25dfe96675abef41829b/href</a></iframe><p>Writing this should generate the following effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*6QvZkFkLKl-ZExn9XXnwXw.png" /><figcaption>Figure 2. Diagram with three different templates for the nodes</figcaption></figure><p>As you can see, the diagram is beginning to take shape. In addition, it’s worth mentioning that besides the appearance of nodes, you can also determine the appearance of edges. This is defined in an analogical manner, with the difference that instead of <strong>nodeTemplate</strong> and <strong>nodeTemplateMap</strong>, we have <strong>linkTemplate</strong> and <strong>linkTemplateMap</strong>, while during the definition of a template, instead of creating a <strong>go.Node</strong> object we create a <strong>go.Link</strong> object.</p><p>You can check out the result of this tutorial here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftswistak%2Fembed%2Fpreview%2FRyOZYM%3Fheight%3D600%26slug-hash%3DRyOZYM%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftswistak%2Fpen%2FRyOZYM&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1194144.RyOZYM.small.af9abe41-697d-41cb-96da-2fb458ab4ba3.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/954128f90cfec71912f0dc8dddf64fdb/href">https://medium.com/media/954128f90cfec71912f0dc8dddf64fdb/href</a></iframe><p>Want more? Check out the<a href="https://itnext.io/creating-simple-application-with-gojs-part-2-c33139e934ba"> second part of this tutorial</a>!</p><p>Post is also published on <a href="http://www.synergycodes.com/blog/">Synergy Codes’ blog</a>, you can check it out <a href="http://www.synergycodes.com/blog/how-do-i-create-a-simple-gojs-application">here</a>.</p><p>Would you like to learn more about GoJS? <a href="https://synergycodes.com/gojs-ebook/">You can download the free ebook here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3c320765def" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/creating-simple-application-with-gojs-part-1-e3c320765def">Creating simple application with GoJS, part 1</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>