<?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 Kolos Farkas on Medium]]></title>
        <description><![CDATA[Stories by Kolos Farkas on Medium]]></description>
        <link>https://medium.com/@sohamar?source=rss-2ffdbbd90778------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vp-N6ZWbsrFOHGgUicOiXg.jpeg</url>
            <title>Stories by Kolos Farkas on Medium</title>
            <link>https://medium.com/@sohamar?source=rss-2ffdbbd90778------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:13:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sohamar/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[Storybook — use a design system]]></title>
            <link>https://medium.com/@sohamar/storybook-use-a-design-system-5329b53bd38d?source=rss-2ffdbbd90778------2</link>
            <guid isPermaLink="false">https://medium.com/p/5329b53bd38d</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Kolos Farkas]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 14:23:33 GMT</pubDate>
            <atom:updated>2023-02-27T14:32:50.986Z</atom:updated>
            <content:encoded><![CDATA[<h3>Storybook — use a design system</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rdFaaMpgJIcDEE5vGJEXA.png" /></figure><h3>Introduction</h3><p>As frontend engineers we have to create some dumb components such as inputs, buttons, radiobuttons, checkboxes etc…<br>One way to create these is to wire them into our already running application and creating them there (styling, wiring in the logic and so). That way could work, but what if we have to show the components to our designer mate, or just demo to our stakeholders? What if we need to share the components with other guys from the company (like we are developing our shared ui library)?<br>So thats why we have Storybook.</p><p>Our another problem is the design of our components. In this article I’ll cover the coloring part of it by creating a dumb component (a button), will wire it into Storybook and create two separate color schemes for it.</p><p><strong>What is storybook?</strong></p><p>Storybook is an open source workshop for component demonstration/development. It also could help us to write documentation and/or test our components.</p><h3>Setting up the environment</h3><p>Lets create a new folder and init storybook within.</p><pre>npx create-react-app sb-demo<br>cd sb-demo<br>npx storybook init<br>npm i # to make sure that we have all the dependencies<br>npm run storybook</pre><p>Once your Storybook is running it will auto open a new browser tab. If wont, open a new tab and navigate to <a href="http://localhost:6006/">http://localhost:6006</a>.</p><p>So as you can see there is Storybook with some predefined stories</p><p><strong>What is a story?</strong></p><p>A story in Storybook is a set of the component’s states. For example a story for a button could have the following statements: primary, secondary, danger (and the other functions), outline, disabled etc… <br>These statements are made by a set of properties so, its not needed to define all of them, but to make everyone’s life easier it worths the plus effort.</p><h3>Creating the button component</h3><p>Lets create a new component within the src folder. At first lets purge Storybooks files from there.</p><pre>cd src<br>rm -r -f stories</pre><p>Then create a new folder called common that will contain our dumb components.</p><pre>mkdir common<br>mkdir common/button<br>cd common/button<br>touch button.jsx<br>touch button.stories.jsx<br>touch button.css<br># open vsc to edit the files<br>cd ../../..<br>code .</pre><p>Okay, so now you have the files you need and the project opened in visual studio code. Lets get work.</p><p>At first lest create the button component:</p><pre>// button.jsx<br>import React from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br><br>import &quot;./button.css&quot;<br><br>const Button = (props) =&gt; {<br><br>    const {<br>        label,<br>        onClick,<br>        type,<br>        isDisabled,<br>        isOutline<br>    } = props;<br><br>    return (<br>        &lt;button<br>            onClick={onClick}<br>            disabled={isDisabled}<br>            className={[<br>                &quot;button&quot;,<br>                `button-${type}`,<br>                isOutline ? &quot;button-outline&quot; : &quot;&quot;<br>            ].join(&quot; &quot;)}<br>        &gt;<br>            { label }<br>        &lt;/button&gt;<br>    )<br>};<br><br>Button.propTypes = {<br>    label: PropTypes.string,<br>    onClick: PropTypes.func,<br>    type: PropTypes.oneOf([<br>        &quot;primary&quot;,<br>        &quot;secondary&quot;,<br>        &quot;info&quot;,<br>        &quot;success&quot;,<br>        &quot;warning&quot;,<br>        &quot;danger&quot;<br>    ]),<br>    isDisabled: PropTypes.bool,<br>    isOutline: PropTypes.bool<br>};<br><br>Button.defaultProps = {<br>    label: &quot;Button&quot;,<br>    type: &quot;primary&quot;,<br>    isDisabled: false,<br>    isOutline: false<br>};<br><br>export { Button }<br></pre><p>So as you can see out button will support the Descartes multiplication of the type and the outline. In the disabled state, the button will be not available for interactions, and will have an opacity effect.</p><p>Now we are done with this, but need to wire the button into Storybook.</p><p>Lets open button.stories.jsx and tell Storybook that we would like to see our new fancy button component.</p><pre>import { Button } from &quot;./button&quot;;<br><br>export default {<br>    title: &quot;Dumb/Button&quot;<br>}<br><br>const Template = (args) =&gt; &lt;Button {...args} /&gt;;<br><br>export const defaultButton = Template.bind({});</pre><p>Once this is done you will see the button in Storybook. But nothing else, its quite silent isn’t it?</p><p>Let’s add some controls to Storybook UI!</p><pre>export default {<br>    title: &quot;Dumb/Button&quot;,<br>    argTypes: {<br>        label: {<br>            control: &quot;text&quot;<br>        },<br>        isDisabled: {<br>            control: &quot;boolean&quot;<br>        },<br>        isOutline: {<br>            control: &quot;boolean&quot;<br>        },<br>        type: {<br>            control: {<br>                type: &quot;select&quot;,<br>                options: [<br>                    &quot;primary&quot;,<br>                    &quot;secondary&quot;,<br>                    &quot;info&quot;,<br>                    &quot;success&quot;,<br>                    &quot;warning&quot;,<br>                    &quot;danger&quot;<br>                ]<br>            }<br>        }<br>    }<br>}</pre><p>Now you can set up the inputs for the button component on the UI.</p><p>The next step is to create some initial cases/states for our new fancy button component.</p><pre><br>export const defaultButton = Template.bind({});<br>defaultButton.props = {<br>    label: &quot;Button&quot;,<br>    isDisabled: false,<br>    isOutline: false,<br>    type: &quot;primary&quot;<br>};<br><br>export const defaultOutlineButton = Template.bind({});<br>defaultOutlineButton.props = {<br>    label: &quot;Button&quot;,<br>    isDisabled: false,<br>    isOutline: true,<br>    type: &quot;primary&quot;<br>};<br><br>export const secondaryButton = Template.bind({});<br>secondaryButton.props = {<br>    label: &quot;Button&quot;,<br>    isDisabled: false,<br>    isOutline: false,<br>    type: &quot;primary&quot;<br>};<br><br>export const secondaryOutlineButton = Template.bind({});<br>secondaryOutlineButton.props = {<br>    label: &quot;Button&quot;,<br>    isDisabled: false,<br>    isOutline: true,<br>    type: &quot;primary&quot;<br>};</pre><p>Okay we are done with the Storybook setup for now. As you can see in Storybook, there are new items in the left side menu, where you can select the initial button states.<br>Since we added the controls as well, you can modify the state once its opened.</p><h3>Creating themes</h3><p>Lets create two theme files and wire them in into our fancy new button component. Once these are done we will style our button component accordingly.</p><p>Navigate back to src folder and create a new folder called assets and a themes folder inside.</p><pre>mkdir assets <br>mkdir assets/themes<br>touch assets/themes/pink-lady.css<br>touch assets/themes/blue-gentle.css</pre><p>Once these are done, lets talk a little about the design system we will use.</p><p>Basically there are named colors in a frontend application — but please note that the naming is not about to color value, but its role within the application. Mainly we have two types of colors: general colors and function colors. In some cases its not enough, so the structure is scalable, in some webapps the header or the footer requires its own colors.</p><p>General colors: primary, secondary and mabye tertiary.<br>Function colors: info, success, warning, danger (not all of them are required).</p><p>Since we would like to put text on a button that have primary background color, we need a new color for that. These colors are prefixed with the on-* string. So the color name we need is on-primary and its the same for the others.</p><p>Another thing we would like to have is the hover state. For that there are multiple ways to do, like opacity, but presonally I prefer the HML system.</p><p><strong>What is the HML system?</strong></p><p>The HML system is named after the high, medium and low. In some applications you could see the posfixes as -h, -m and -l or -hi, -med and -lo. There are examples where they are used by their full name. I prefer the single-letter approach.</p><p>The HML system is defined by the following rule (it is my own rule, you may not like it 🙂)</p><blockquote>Medium is the median value, low is 10% darker and light is 10% brighter.</blockquote><p>The 10% is not a hardcoded value, and since we wont use SASS in this project we cannot use darken() and lighten() functions. So for now I’ll hardcode all the values.</p><p><strong>Thumb of rule</strong>: These colors are always should come from the UI/UX guild, so we — as developers — are not responsible for inventing, but only for implementing.</p><p>So after the thing discussed above, lets fill up the two files we made earlier.</p><pre>/* blue-gentle.css */<br>body.blue-gentle {<br>    --primary-l: #001D4E;<br>    --primary-m: #002157;<br>    --primary-h: #003181;<br><br>    --on-primary-l: #E5E5E5;<br>    --on-primary-m: #FFFFFF;<br>    --on-primary-h: #FFFFFF;<br><br>    --secondary-l: #Ef0810;<br>    --secondary-m: #F71D25;<br>    --secondary-h: #F7333A;<br><br>    --on-secondary-l: #E5E5E5;<br>    --on-secondary-m: #FFFFFF;<br>    --on-secondary-h: #FFFFFF;<br>}<br><br>/* pink-lady.css */<br>body.pink-lady {<br>    --primary-l: #F976AC;<br>    --primary-m: #FB9EC4;<br>    --primary-h: #FBA7C9;<br><br>    --on-primary-l: #E5E5E5;<br>    --on-primary-m: #FFFFFF;<br>    --on-primary-h: #FFFFFF;<br><br>    --secondary-l: #FFBF93;<br>    --secondary-m: #FFDAC0;<br>    --secondary-h: #FEDDC6;<br><br>    --on-secondary-l: #E5E5E5;<br>    --on-secondary-m: #FFFFFF;<br>    --on-secondary-h: #FFFFFF;<br>}</pre><p>As you can see I’ve implemented the primary and secondary colors only for save some time and space. The classes are attached to the body. The reason behind:</p><ul><li>its easy to modify with any framework or even with vanilla js</li><li>the scope is quite big so all the content will get the CSS variables</li><li>works with ShadowDom — and to be fair I’m not sure about webcomponents</li></ul><p>The last thing we have to do is to tell Storybook that we need these CSS files — in terms of a webapplication we have to import them somehow as well.</p><p>So to inject them into Storybook, we have to edit ./.storybook/preview.js.</p><p>Lets add the two lines to that file</p><pre>import &quot;../src/assets/themes/blue-gentle.css&quot;; // new css import<br>import &quot;../src/assets/themes/pink-lady.css&quot;;   // new css import<br><br>export const parameters = {<br>  actions: { argTypesRegex: &quot;^on[A-Z].*&quot; },<br>  controls: {<br>    matchers: {<br>      color: /(background|color)$/i,<br>      date: /Date$/,<br>    },<br>  },<br>}</pre><p>And if you open Storybook now, and add any of the classes into the body element inside the iframe, you’ll get the colors — but they wont do anything. Being there and staying awesome is a very good thing isn’t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDeUFORWPsUnH9o3FhpM5w.png" /><figcaption>Pink lady colors in Storybook</figcaption></figure><h3>Creating a theme switcher addon for Storybook</h3><p>So we have our component there and we have our style/theme files. But we have to find a way to give the control to the end-user to be able to select them.</p><p>Fortunately Storybook support addon development and they even have a complete guide to create a theme switcher.</p><p>Lets add the following to the ./.storybook/preview.js.</p><pre>export const globalTypes = {<br>  theme: {<br>    name: &quot;Theme&quot;,<br>    title: &quot;Theme&quot;,<br>    description: &quot;Theme for your application&quot;,<br>    defaultValue: &quot;blue-gentle&quot;,<br>    toolbar: {<br>      icon: &quot;paintbrush&quot;,<br>      dynamicTitle: true,<br>      items: [<br>        { value: &quot;blue-gentle&quot;, title: &quot;Blue Gentle&quot; },<br>        { value: &quot;pink-lady&quot;, title: &quot;Pink Lady&quot; },<br>      ],<br>    },<br>  },<br>};</pre><p>This code will add a new item into the toolbar on the top. You can select the theme by clicking on the toolbar (by default it will be Blue Gentle.</p><p>So for now on we are able to select a theme, but nothing happens. Why?<br>Because we have to modify the document we render to have the proper class added.</p><h3>Creating a decorator for Storybook</h3><p>So in the segment above we made an addon that helps us to select a theme, but we have to use it somehow. The official Storybook documentation says that the best approach would be a wrapper that contains the custom CSS variables, but what if we’d like to have 1:1 reproduction of our production code?</p><p>So we can agree on that we’ll need a Storybook decorator, but we would like to modify the document body, not a wrapper. This sounds like a hacky solution, and I’m not going to argue, yes it is a hacky solution. But in such cases it’s ok to have hacky solutions.</p><p>Change ./.storybook/preview.js accordingly:</p><pre>const themeDecorator = makeDecorator({<br>  wrapper: (getStory, context, { parameters }) =&gt; {<br>    const story = getStory(context);<br>    const theme = context.globals.theme;<br>    const sbClasses = Array.from(document.body.classList).filter(m =&gt; m.startsWith(&quot;sb-&quot;));<br>    document.body.className = &quot;&quot;;<br>    [<br>      ...sbClasses,<br>      theme<br>    ].forEach(m =&gt; document.body.classList.add(m));<br>    return story;<br>  }<br>});<br><br>export const decorators = [<br>  themeDecorator<br>];</pre><p>What this does? I’ve made a decorator that allows story modification before rendering. The rendering happens when a theme got changes (any of the globals changes). The decorator checks the classes on the body element, and stores the storybook related ones (they starts with sb-) and adds the selected theme’s class.</p><p>Then returns the story itself without any modifications.</p><h3>Styling the button component using the defined colors</h3><p>The last thing we have to do is write our styles for the button. Please remember that we have all the colors in global scope, so we should use those.</p><p>For the rest (spacing, typography and so) I’ll use hardcoded values, but such values could be added (and should be added!) to a proper design system.</p><pre>.button {<br>    border-radius: 4px;<br>    padding: 8px 24px;<br>    border: 1px solid;<br>    text-transform: uppercase;<br>    font-family: &quot;Gill Sans&quot;;<br><br>    box-sizing: border-box;<br>    -moz-box-sizing: border-box;<br>    -webkit-box-sizing: border-box;<br>}<br><br>.button:disabled {<br>    pointer-events: none;<br>    opacity: 0.5;<br>}<br><br>.button:hover,<br>.button:active {<br>    cursor: pointer;<br>}<br><br>.button:active {<br>    text-decoration: underline;<br>}<br><br>.button.button-primary {<br>    color: var(--on-primary-m);<br>    background-color: var(--primary-m);<br>}<br><br>.button.button-secondary {<br>    color: var(--on-secondary-m);<br>    background-color: var(--secondary-m);<br>}<br><br>.button.button-primary:hover {<br>    color: var(--on-primary-l);<br>    background-color: var(--primary-l);<br>}<br><br>.button.button-secondary:hover {<br>    color: var(--on-secondary-l);<br>    background-color: var(--secondary-l);<br>}<br><br>.button.button-outline.button-primary {<br>    color: var(--primary-m);<br>    background-color: var(--on-primary-m);<br>}<br><br>.button.button-outline.button-secondary {<br>    color: var(--secondary-m);<br>    background-color: var(--on-secondary-m);<br>}<br><br>.button.button-outline.button-primary:hover {<br>    color: var(--primary-l);<br>    background-color: var(--on-primary-l);<br>}<br><br>.button.button-outline.button-secondary:hover {<br>    color: var(--secondary-l);<br>    background-color: var(--on-secondary-l);<br>}</pre><p>So as you can see we have to set up the common properties once in the .button class. The rest are about the button’s states and parameters such as :hover or :active and :disabled as states and primary or secondary and outline as parameters.</p><p>So thats all about a design system in Storybook, I hope I’ve teached you something new. Feel free to reach me out on LinkedIn or here in Medium if you have any questions.<br>I hope you find this article useful later, and will benefit from it.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5329b53bd38d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typescript enums]]></title>
            <link>https://medium.com/@sohamar/typescript-enums-3debfbd59138?source=rss-2ffdbbd90778------2</link>
            <guid isPermaLink="false">https://medium.com/p/3debfbd59138</guid>
            <category><![CDATA[compilation]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[code-optimization]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kolos Farkas]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 05:17:47 GMT</pubDate>
            <atom:updated>2022-07-03T13:31:17.270Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enumeration in Typescript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*BgC7MduO4YWfbVQUIHSg4w.png" /></figure><p>As software engineers we cannot avoid enumerations in our projects. Enumeration is a language independent solution to store a value with a string representation.</p><p>In different languages we have different solutions to do that:</p><h3>C#</h3><p>C# is the most powerful backend language developed by Microsoft. It has a lot of powerful stuff like enums.</p><pre>public enum Color {<br> Red = 1;<br> Green = 2;<br> Blue = 3;<br>}</pre><p>In C# an enum represents a numeric value, could be cast into a string with the .ToString() extension method, and sometimes an enum could contain more than one value.</p><pre>var redOrGreen = Color.Red | Color.Green;</pre><p>But in the above chase the [Flags] <a href="https://docs.microsoft.com/en-us/dotnet/api/system.flagsattribute">attribute</a> should be added to the enum.</p><h3>JavaScript</h3><p>Javascript does not have native support for enum, but there are ways to do it.</p><p><strong>Enum as const properties<br></strong>In this case we are creating public static properties on a class. We can use the properties without creating the class instance. Not the best solution but it could work.</p><pre>class Color {<br> static Red = 1;<br> static Green = 2;<br> static Blue = 3;<br>}</pre><p>As I mentioned earlier, we not love this solution, because JS is a prototype based OOP language, which means it doesnt like the static keyword. To avoid that we should find a better solution.</p><p><strong>Enum as an object<br></strong>Instead of creating an antipatternish class with static properties we could create an object, and use it as an enum.</p><pre>const Color = Object.freeze({<br> Red : 1,<br> Green: 2,<br> Blue: 3<br>});</pre><p>In the code above I’ve used the Object.freeze() utility function to mark my object as readonly. The object cannot be modified in runtime.<br>We could use the above object as an enum.</p><p>In both JS examples we could use different types in the enum. Not just primitives such as string, number and bool, but complex object types such as object and array.</p><h3>TypeScript</h3><p>In TS we could use both the JS approaches, but we have native enum support in TS. Lets see the possibilites with TypeScript enums.</p><p><strong>export enum<br></strong>Export enum is a very easy way to create an enum in typescript which exists in runtime as well.</p><pre>export enum Color {<br> Red = 1,<br> Green = 2,<br> Blue = 3<br>};</pre><p>But, the code above will compile into this:</p><pre>export var Color;<br>(function (Color) {<br>    Color[Color[&quot;Red&quot;] = 1] = &quot;Red&quot;;<br>    Color[Color[&quot;Green&quot;] = 2] = &quot;Green&quot;;<br>    Color[Color[&quot;Blue&quot;] = 3] = &quot;Blue&quot;;<br>})(Color || (Color = {}));</pre><p>So, we will have an object Color with the defined properties (Red , Green and Blue), but the object will have the values as properties as well (1 , 2 and 3).<br>If we log the Color object, we will get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*w-cdpvDdQdBgWk0iScvHLw.png" /><figcaption>Figure 1 — Enum logged in runtime</figcaption></figure><p>So, in short, export enum in Typescript is very good, if we are creating a library, as we need the enum in runtime. But in most cases, we are creating enums to store a type such as gender. Do we need that information in runtime? The answer is no. We could “hardcode” it into our code.</p><p><strong>export const enum<br></strong>This is the another approch in Typescript. We can create an export const enum, which contains the data we need, but <strong>it wont be available in runtime</strong>. Lets create a const enum:</p><pre>export const enum Color {<br> Red = 1,<br> Green = 2,<br> Blue = 3<br>}</pre><p>This code wont be compiled into Javascript:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTLeOJ5V78nxHhC6He3L8w.png" /><figcaption>Figure 2 — Const enum compilation result</figcaption></figure><p>This means, if we create a const enum, it wont be a part of our bundle by default, so we have to use it.</p><pre>const red = Color.Red;<br>const green = Color.Green;<br>const blue = Color.Blue;</pre><p>If we compile the code above, we will get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*BAoD2xcs94X28M_XIWxw7w.png" /><figcaption>Figure 3 — Const enum usage</figcaption></figure><p>This means, if we have a const enum in our code, then we can think on it as a hardcoded value. The best approach is project-dependent as nearly everything in software development.</p><p><strong>Plus one: types<br></strong>In Typescript we could define a type which will behave like a const enum. types wont be a part of our distribution (javascript) file, but as the const enums they could be found in the *.d.ts files.</p><pre>export type Color = &quot;Red&quot; | &quot;Green&quot; | &quot;Blue&quot;;</pre><p>As you can see above, a type cannot carry any additional information. In some cases it worths to use a type instead of a const enum, but it makes the code harder to read and maintain. I’d suggest to use a custom type. When the related code wont be extended. But there is the question again:</p><p>Do we need to chain down our hands with types?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3debfbd59138" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack seed for FE applications]]></title>
            <link>https://medium.com/@sohamar/webpack-seed-for-fe-applications-674cd38c0678?source=rss-2ffdbbd90778------2</link>
            <guid isPermaLink="false">https://medium.com/p/674cd38c0678</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[application-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Kolos Farkas]]></dc:creator>
            <pubDate>Sat, 04 Jun 2022 14:30:55 GMT</pubDate>
            <atom:updated>2022-07-03T13:36:30.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>Webpack webseed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*4dGqeemMwUf0VFVDDsik4Q.png" /></figure><p>As a frontend engineer, I’m also thinking about a pet project. Mainly not in angular, since it is overkill for a small todo app or an end-to-end encrypted chat. What else do we have — from my elbow?</p><ul><li>react</li><li>vue</li><li>svelte</li><li>knockout</li><li>mithril</li></ul><p>React, Vue and Svelte are too famous for me, I’d like to use something “<em>old but good</em>” such as knockout, or something “<em>swiss-blade</em>” like mithril. But those are written in vanilla, and dont have built-in bundling, dev server and such magic. So what did I have to do? The whole time I had to create my own development environment, and it became boring. So I’ve decided to create my own seed, push it to my github repository and use it as a template when needed.</p><p>At first, we have to set up our goals:</p><p>The package should</p><ul><li>have a built-in dev server with change detection / HMR</li><li>support typescript</li><li>support SASS</li><li>support HTML loading</li><li>does not have dist folder (so the build process should generate the index.html file)</li><li>industry standard script commands</li></ul><p>For those I’ve decided to use webpack with a few plugins</p><ul><li>webpack</li><li>webpack-dev-server</li><li>webpack-html-plugin</li><li>ts-loader</li><li>sass-loader with mini-css-extract-plugin</li></ul><h3>Lets get started</h3><p>At first lets create our container folder, lets call it webpack-seed, this folder will contain all of our files. Inside the folder we have to create our package.json file, which will contain all of our dependencies and scripts. Inside the file, lets add some dependencies at first:</p><pre>{<br>  &quot;devDependencies&quot;: {<br>    &quot;webpack&quot;: &quot;~5.72.1&quot;,<br>    &quot;webpack-cli&quot;: &quot;~4.9.2&quot;<br>  }<br>}</pre><p>These two dependencies will help us a lot. Lets see how!</p><p><strong>webpack</strong>: webpack is a node application which will bundle our javascript files together. Since most of the frontend engineers use typescript, and would like to create style files, webpack has to support these as well. For this, webpack gives you the opportunity, to precompile your typescript files into javascript with a plugin, then bundle them together.</p><p><strong>webpack-cli</strong>: as it is written, webpack-cli is a command line interface for webpack.</p><p>Once we are done, we have to add some another dependencies to enable typescript and sass compiling. But first, lets install our dependencies, and add our first plugin.</p><p>So before installing the dependencies, lets add another dependency to the package.json file.</p><pre>&quot;devDependencies&quot;: {<br>  &quot;html-webpack-plugin&quot;: &quot;~5.5.0&quot;<br>  ...<br>}</pre><p>HTMLWebpackPlugin will help us to have an index.html file once the bundling is done. We need this, because we will use chunks in filenames. To demonstrate that, lets create our webpack.config.json file in the root folder, with the following contents:</p><pre>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);<br>const path = require(&#39;path&#39;);</pre><pre>const config = () =&gt; {<br>  const cfg = {<br>    output: {<br>      path: path.resolve(__dirname, &#39;./dist&#39;),<br>      filename: &#39;bundle.js&#39;<br>    },<br>    plugins: [<br>      new HtmlWebpackPlugin()<br>    ]<br>  };<br>  return cfg;<br>};</pre><pre>module.exports = config;</pre><p>In the config above, we set the output path, what will be the ./dist folder (relative to the current path), and the output filename will be bundle.js. In the plugins array we create a new instance of the HtmlWebpackPlugin without any configuration for now. At the end we will export the function, so webpack can read that. Lets install the dependencies. Once it is done, we have to do one more thing:</p><p><strong>We should give something for webpack to bundle.</strong></p><p>So, inside our root folder, lets create a folder called src and put javascript into it. I’d use index as the filename for now, but later when we are really creating our environment seed, I’ll use a different name.</p><p>Put a simple alert to that javascript file:</p><pre>alert(&quot;hello world!&quot;);</pre><p>Now if we run npx webpack webpack will bundle our javascipt files into the dist folder and the html plugin will create a sample index.html file for us as well.</p><p>The first step is done!</p><h3>Lets add some typescript into the soup!</h3><p>To use typescript, we have to install some dependencies. Lets modify our package.json file to have the following devdependencies:</p><pre>{<br>  &quot;devDependencies&quot;: {<br>    ...<br>    &quot;typescript&quot;: &quot;~4.7.2&quot;,<br>    &quot;ts-loader&quot;: &quot;~9.3.0&quot;<br>  }<br>}</pre><p>ts-loader is a loader plugin for webpack. It will transform the file before webpack tries to bundle it.</p><p>typescript is the original typescript package from Microsoft, which comes with tsc (Typescript Compiler).</p><p>To use those, we have to modify our webpack configuration as well, with the following:</p><pre>plugins: [<br>  new HtmlWebpackPlugin()<br>],<br>module: {<br>  rules: [<br>    {<br>      test: /\.ts$/,<br>      use: &quot;ts-loader&quot;,<br>      exclude: /node_modules/<br>    }<br>  ]<br>},<br>resolve: {<br>  extensions: [&quot;.ts&quot;, &quot;.js&quot;]<br>}</pre><p>What does it do? We set a rule for filenames ending with .ts to run through the ts-loader package, to get compiled into Javascript files. We have to exclude the node-modules folder, since it should contain compiled javascript files, and we dont want to compile the *.d.ts files.</p><p>For webpack we have to tell we would like to resolve a typescript files only, and js files if they are needed (for example files from node_modules).</p><p>Now its time to install our newly added and configured dependencies.</p><p>Before we run webpack again, we have to configure typescript as well.<br>Lets create a new file next to our webpack.config.js name it as tsconfig.json and add the following content into it:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;allowJs&quot;: false,<br>    &quot;lib&quot;: [&quot;DOM&quot;, &quot;ES2015&quot;],<br>    &quot;moduleResolution&quot;: &quot;Node&quot;<br>  }<br>}</pre><p>With that configuration we disable javascript files, and as dependency typescript libs we add the DOM module, because we would like to interact with the DOM later, and ES2015, because it supports a lot of useful things. For moduleResolution I suggest to use Node. Take a look at NodeJS <a href="https://nodejs.org/api/modules.html#modules_all_together">specification</a> if you are interested in that.</p><p>Before we run the application, lets rename our javascript file to a typescript one, then run webpack again.</p><h3>We need to control our index.html file</h3><p>From now we have a working typescript seed, but what if we need a custom html file (for example a div in it)? We have to create our custom html file before bundling, but we dont want to push our dist folder to github, and doesnt want to edit it manually.</p><p>Fortunately HTMLWebpackPlugin gives the opportunity, to use an existing html file as template. Lets add an index.html file into our src folder.</p><p>Add the following content into the newly created html file:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Webpack seed&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    Hello templating!<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now we have a customizable html template, but we have to tell HTMLWebpackPlugin to use this file as a template. Do you remember, when we added the plugin to our webpack config? Lets modify that line as below:</p><pre>plugins: [<br>  new HtmlWebpackPlugin({<br>    template: &quot;./src/index.html&quot;,<br>    minify: false<br>  })<br>]</pre><p>The template property describes an existing file for the plugin to use it as a template. As we expected. Since the plugin will parse the file content as HTML, we had to add the html, body and head tags. The minify property helps us to generate readable html at the end. Lets run webpack again, and check the changes.</p><h3>Ok, its time for CSS</h3><p>Since we have a customized html file and our typescript compiles into javascript, we have to add one more thing to our application seed. The SASS loading. SASS is a precompiler for CSS, what helps us to avoid code-repeating and with a lot of other stuff.</p><p>At first we have to add some new dependencies:</p><pre>{<br>  &quot;devDependencies&quot;: {<br>    ...<br>    &quot;css-loader&quot;: &quot;~6.7.1&quot;,<br>    &quot;mini-css-extract-plugin&quot;: &quot;~2.6.0&quot;,<br>    &quot;sass-loader&quot;: &quot;~13.0.0&quot;<br>  }<br>}</pre><p>Once they are there, we have to modify our webpack config:</p><ul><li>we have to add the MiniCssExtractPlugin to the plugins array, with its configuration</li><li>we have to add a new rule for .scss files</li></ul><pre>plugins: [<br>  ...<br>  new MiniCssExtractPlugin({<br>    filename: &quot;bundle.css&quot;<br>  })<br>],<br>module: {<br>  rules: [<br>    {<br>      test: /\.scss$/,<br>      use: [<br>        MiniCssExtractPlugin.loader,<br>        {<br>          loader: &quot;css-loader&quot;,<br>          options: {<br>            modules: true,<br>            sourceMap: true,<br>            importLoaders: 2<br>          }<br>        },<br>        &quot;sass-loader&quot;<br>      ],<br>    },<br>  ]<br>},</pre><p>One last thing before we could install our dependencies and run the build again. We have to create a style file next to the index.ts file and import it.</p><p>Lets create our styles.scss file with the following content:</p><pre>html,<br>html &gt; body {<br>  padding: 0;<br>  margin: 0;<br>  width: 100%;<br>  height: 100%;<br>}</pre><p>Before we run it, we have to import it into our index.ts file. Lets add the following to the typescript file: import &quot;./styles.scss&quot;; aaaaand thats it! We are done with our basic skeleton.</p><p>And now, lets build our application with webpack, and run the index.html file from the dist folder.</p><h3>Its time to polish the seed</h3><p>For now we have our application done, but our source looks a little bit messy. How to fix that?</p><ul><li>We need the index.ts file, since it is the default file what webpack will look for. Its always a good idea to use the defaults.</li><li>We would like to have our hands on the application bootstrapping.</li><li>We have to load the style files.</li><li>We have to recompile our application all the time we made a change. Its a waste of time.</li></ul><p>So at first, lets create an app folder inside the src folder, and put a typescript file into it. Here is the content:</p><pre>export class WebpackSeedApp {<br>  constructor() {<br>    const body = document.body as HTMLBodyElement;<br>    const textNode = document.createTextNode(&quot;Hello world!&quot;);<br>    const span = document.createElement(&quot;span&quot;);<br>    span.appendChild(textNode);<br>    body.appendChild(span);<br>  }<br>}</pre><p>Now we have to create our bootstrap.ts file next to the index.ts with the following content:</p><pre>import { WebpackSeedApp } from &quot;./app/app&quot;;</pre><pre>function bootstrap() {<br>  new WebpackSeedApp();<br>}</pre><pre>document.addEventListener(&quot;DOMContentLoaded&quot;, bootstrap);</pre><p>It will run the app when the DOM is loaded. The last thing is to modify the existing index.ts file:</p><pre>import &quot;./styles.scss&quot;;<br>import &quot;./bootstrap&quot;;</pre><p>And thats it, lets rebuild our application and check the changes!</p><p><strong>But what about rebuilding?</strong></p><p>With webpack we could use webpack-dev-server, to host our application and automatically rebuild our code.</p><p>Lets configure our webpack to do that!<br>At first — as usual — we have to add a new dependency:</p><pre>{<br>  &quot;devDependencies&quot;: {<br>    ...<br>    &quot;webpack-dev-server: &quot;~4.9.0&quot;<br>  }<br>}</pre><p>Now, lets configure webpack to use the devServer:</p><pre>{<br>  ...<br>  resolve: {<br>    extensions: [&quot;.ts&quot;, &quot;.js&quot;]<br>  },<br>  devServer: {<br>    static: {<br>      directory: path.join(__dirname, &quot;dist&quot;),<br>    },<br>    compress: true,<br>    port: 9000,<br>  }<br>}</pre><p>Now we have our webpack-dev-server configured properly, but we have to do some steps before we could use our application seed.</p><p>At first we have to write our scripts into the package.json file.</p><pre>...<br>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;webpack --env development&quot;,<br>  &quot;build:prod&quot;: &quot;webpack --env production&quot;,<br>  &quot;serve&quot;: &quot;webpack serve --env development&quot;<br>}<br>...</pre><p>And we have to use the environment variables in our webpack config:</p><pre>const config = (env) =&gt; {<br>  const isProduction = env.production;<br>  const cfg = {<br>    mode: isProduction ? &quot;production&quot; : &quot;development&quot;,<br>    output: {<br>      path: path.resolve(__dirname, &quot;./dist&quot;),<br>      filename: isProduction ? &quot;bundle.min.js&quot; : &quot;bundle.js&quot;<br>    },<br>    plugins: [<br>     new HtmlWebpackPlugin({<br>      template: &quot;./src/index.html&quot;,<br>      minify: isProduction<br>    }),<br>    new MiniCssExtractPlugin({<br>      filename: isProduction ? &quot;bundle.min.css&quot; : &quot;bundle.css&quot;<br>    })<br>],<br>...</pre><p>Aaaaand we are done!</p><p>The code of this seed could be found in my <a href="https://github.com/SOHAMAR/webpack-seed">github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=674cd38c0678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching the goldfish — memoization]]></title>
            <link>https://medium.com/@sohamar/teaching-the-goldfish-memoization-3a48ce7e8e0d?source=rss-2ffdbbd90778------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a48ce7e8e0d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Kolos Farkas]]></dc:creator>
            <pubDate>Mon, 09 May 2022 19:21:31 GMT</pubDate>
            <atom:updated>2022-07-03T14:35:03.905Z</atom:updated>
            <content:encoded><![CDATA[<h3>Teaching the goldfish — memoization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*tH4PjhRappbqjzID.jpg" /><figcaption>The server when the expensive method hits!</figcaption></figure><p>Since we — humans — are using machines to work for us, we could do our daily job faster. From the very beginning, human beings use different resources such as wind, water, solar energy to in help their daily routines.</p><p>In the 19th century Babbage built his own computer — the first one! He used that computer to do his calculations faster. Since then tons of engineers are trying to create faster and better computers. But there is an issue, the Moore-law. We are not able create smaller parts for our computers, so we couldn’t make faster computer by using more, smaller parts.</p><p>The other way to make our computers and applications faster, is programming. We are using high-level languages: C#, Java, Typescript, Javascript, PHP and such.<br>These languages are “slow” in terms of a processor. Just think about it, our processors frequency is in the gigahertz range, but the smallest measurable timerange is about milliseconds in C#.</p><pre>1GHz = 1000000000Hz = 1*10^9Hz</pre><pre>[Hz] = 1/[s]<br>1/10^9MHz = 10^-9s</pre><pre>1ms = 0.001s = 1*10^-3s</pre><pre>1*10^-3s &lt;&gt; 1*10^-9s<br>What?</pre><p>So as you can see, we lost two scales of time. In a way, we could re-learn low-level languages such as assembly languages, C, C++, but as we all know, it is quite hard for most of us.</p><h3>What else could we do?</h3><p>As developers we are writing code, creating applications which are automating workflows. And within those workflows there is always a step which requires a long-running expensive calculation. And we have to call that calculation too many times (more than once), with the same arguments.</p><p>In such cases most of the developers are about to create a cache or a state management solution. Such as me.</p><p>A state management system could be good, to store the precalculated value for a single token. For example different options, allowed actions, event log for a specific (logged in) user.<br>A cache is good, for storing that information with a unique identifier. The identifier could be the user id, if we follow the above example.</p><p>But could we do it in a cheaper way? To be honest yes, we could use memoization on the specified calculation method.</p><p>In short, we need two things:</p><ul><li>A pure function which could be memozied</li><li>A cache, what could store our values</li></ul><p>Given the two required things, we could start creating our memoization logic. Lets start with the pseudo code:</p><pre>function thisFunctionShouldBeMemoized(arg1, arg2, ... argN) {<br>  keyInCache = generateCacheKeyBasedOnTheArgs();<br>  valueInCache = cache.get(keyInCache);<br>  if(!valueInCache) {<br>    // do the expensive logic here<br>    // and set the result into the cache<br>  }<br>  return cache.get(keyInCache)<br>}</pre><p>As you can see, we try to read the existing value from the cache, and return it if we have any. If we dont have it, then we have to calculate it.</p><p>Lets modify our code a little, to make it clearer, and move away from this pseudo-like approach.</p><pre>const cache = {};</pre><pre>function memoize(calculator: Function, arguments: unknown[]) {<br>  const key = generateKeyFromArguments(arguments);<br>  const hasValue = Object.keys(cache).includes(key);<br>  if(!hasValue) {<br>    cache[key] = calculator.apply(this, arguments);<br>  }<br>  return cache[key];<br>}</pre><pre>// Usage<br>memoize(doSomethingExpensive, [1, 2]);</pre><p>I’ve used Typescript to create my demo, but there is much more to do. As you can see, the arguments parameter should be an array, what we dont want to do. So how can we improve on that?</p><p>In Typescript we could create custom decorators. Basically a decorator is a function which will be run when the instance has been created. With a very-easy lift trick, we could modify our existing function to be wrapped by our memoize logic. This trick will make our memoize decorator reuseable.</p><p>Lets create our memoize decorator:</p><pre>// memoize.ts</pre><pre>const cache = {};</pre><pre>export function MemoizeDecorator() {<br>  return (<br>    target: any,<br>    propertyKey: string,<br>    descriptor: propertyDescriptor) =&gt;<br>  {<br>    const lifted = descriptor.value;<br>    const newFn = function() {<br>      const args = arguments;<br>      const cacheKey = JSON.stringify(args);<br>      if(!Object.keys(cache).includes(cacheKey)) {<br>        cache[cacheKey] = lifted.apply(this, args);<br>      }<br>      return cache[cacheKey];<br>    }<br>    descriptor.value = newFn;<br>  }<br>}</pre><pre>// Usage:<br>@MemoizeDecorator()<br>public myExpensiveFunction(arg1: string, arg2: number) {<br>  // ...<br>}</pre><h4>What does my code really do?</h4><p>I’ve created a factory decorator. This returns another function. The returned function has three parameters, what would be given in runtime. The first one is the target which refers to the instance which contains the given method. The propertyKey is the name of the given method. The last one is the descriptor which describes the property itself. It has a property value which contains the method itself. When we override the descriptor.value property, we are really touching the function.</p><p>In the code above, I’ve lifted the original function, wrapped it by the memoization logic, then reassigned the new function to the original value. With this, I can call the function in the expected way, but will decrease the run time, when the function is called multiple times.</p><p>Lets write a simple testing code:</p><pre>import { MemoizeDecorator } from &quot;./memoize&quot;;</pre><pre>export class Demo {</pre><pre>  @MemoizeDecorator()<br>  public async aVeryExpensiveFunctionWhichReturn3() {<br>    return new Promise((resolve) =&gt; {<br>      setTimeout(() =&gt; resolve(3), 1000);<br>    });<br>  }<br>}</pre><p>The code above will wait one second, then will return 3. Now we need only one thing, test the above code. For that we have to create an instance of the Demo class, and call the aVeryExpensiveFunctionWhichReturn3() function multiple times. During the calls we should count the elapsed time.</p><p>Here we go:</p><pre>async function test() {<br>  const instance = new Demo();<br>  const begin1 = new Date().getTime();<br>  const r1 = await instance.aVeryExpensiveFunctionWhichReturn3();<br>  console.log(&quot;result 1&quot;, r1);<br>  const end1 = new Date().getTime();<br>  const begin2 = new Date().getTime();<br>  const r2 = await instance.aVeryExpensiveFunctionWhichReturn3();<br>  console.log(&quot;result 2&quot;, r2);<br>  const end2 = new Date().getTime();<br>  console.log(&quot;time diff 1&quot;, (end1 - begin1) / 1000);<br>  console.log(&quot;time diff 2&quot;, (end2 - begin2) / 1000);<br>}</pre><p>Only one thing left: Run the test code, and check the output.</p><pre>RESULT:</pre><pre>$ npx tsc &amp;&amp; node ./src/main.js<br>result 1 3<br>result 2 3<br>time diff 1 1.015<br>time diff 2 0</pre><p>I’ve used tsc to compile my code and node to run it. As it shows, the first run took a little bit more than 1s because the memoization logic itself has some latency. But for the 2nd loop it used less than a millisecond which means, the code read the precalculated value from the cache.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a48ce7e8e0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>