<?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 Aleksandr Kubarskii on Medium]]></title>
        <description><![CDATA[Stories by Aleksandr Kubarskii on Medium]]></description>
        <link>https://medium.com/@sasha.kub95?source=rss-6835a67ac4ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6qUrRGHPqsLK3a5p</url>
            <title>Stories by Aleksandr Kubarskii on Medium</title>
            <link>https://medium.com/@sasha.kub95?source=rss-6835a67ac4ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:05:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sasha.kub95/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[Creating 3D text engine in the browser]]></title>
            <link>https://itnext.io/creating-3d-text-engine-in-the-browser-7dd8fc294ac5?source=rss-6835a67ac4ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dd8fc294ac5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-frameworks]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aleksandr Kubarskii]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 00:14:38 GMT</pubDate>
            <atom:updated>2026-02-27T00:14:38.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*0KbeVyXKxZoguSxnB1umqw.png" /></figure><p>TL;DR</p><p>Here’s the link to the project demo page and my github:<br>1. <a href="https://github.com/kubarskii/text-3d-engine">Github</a><br>2. <a href="https://kubarskii.github.io/text-3d-engine/">Demo </a><br>3. <a href="https://kubarskii.github.io/text-3d-engine/text-demo.html">Demo2</a></p><p>Honestly, when I first decided to play a bit with 3D, I thought that it was extremely complex. But to create something similar, you could see, requires just some basics of trigonometry and 1 formula to actually transform x, y and z coordinates into 2D projection.</p><p>In a shot, here it is:</p><pre>export const normalizeZ = ({ x, y, z }) =&gt; {<br>    if (z &lt;= 0) {<br>        return { x: 0, y: 0 }<br>    }<br>    return { x: x / z, y: y / z }<br>}</pre><p>What it does is simply move dots closer to the center of the screen, the farther the object is.</p><p>Now lets add some more details. The project requires:<br>- No WebGL. <br>- No external 3D libraries. <br>- Just math and the browser.</p><h3>Step 1: Representing Text in 3D</h3><p>Instead of generating real 3D meshes or using font triangulation, I took a simpler approach:</p><p>Each character is represented as a set of 3D points and edges.</p><p>Conceptually:</p><pre>type Point3D = {<br>  x: number<br>  y: number<br>  z: number<br>}</pre><p>Letters are defined as 2D shapes and then “extruded” along the Z axis.</p><p>So a flat letter becomes a 3D object with depth.</p><p>Internally, the model looks like:</p><pre>{<br>  vertices: Point3D[],<br>  edges: [number, number][]<br>}</pre><p>Edges define which vertices should be connected with lines. This makes the engine essentially a <strong>wireframe renderer</strong>.</p><h3>Step 2: Rotating in 3D</h3><p>Rotation sounds intimidating, but it’s just sine and cosine.</p><p>For example, rotation around the Y axis:</p><pre>x&#39; = x * cos(θ) - z * sin(θ)<br>z&#39; = x * sin(θ) + z * cos(θ)</pre><p>Rotation around the X axis:</p><pre>y&#39; = y * cos(θ) - z * sin(θ)<br>z&#39; = y * sin(θ) + z * cos(θ)</pre><p>In the engine, every frame:</p><p>- Take original vertices<br>- Apply scaling<br>- Apply rotation<br>- Translate into camera space<br>- Project to 2D</p><p>That’s basically the same pipeline real 3D engines use, but without matrices (yet).</p><h3>Step 3: ASCII Framebuffer</h3><p>Instead of drawing to &lt;canvas&gt;, the engine renders into a 2D character buffer.</p><p>Internally:</p><pre>chars[y][x]<br>depth[y][x]</pre><p>chars stores the ASCII character to display<br>depth stores the closest Z value for that cell</p><p>This is a simple <strong>Z-buffer</strong> implementation.</p><p>When drawing a line:</p><ul><li>Interpolate X, Y, and Z</li><li>For each step:<br>- If the current Z is closer than the stored depth<br>- Replace the character</li></ul><p>That’s proper depth testing — even in ASCII.</p><h3>Step 4: Shading With Characters</h3><p>To improve the 3D illusion, I added depth-based shading:</p><pre>const SHADE_CHARS = &#39; ·∙░▒▓█&#39;</pre><p>Closer edges use heavier characters like █.<br>Further edges use lighter ones like ·.</p><p>So even though we’re only drawing lines, the model feels volumetric.</p><p>No lighting model.<br>No normals.<br>Just character gradients.</p><p>And it works surprisingly well.</p><h3>Step 5: Near Clipping</h3><p>One subtle but important improvement was near clipping.</p><p>If a line crosses the near plane (z close to 0), perspective projection becomes unstable.</p><p>So before projection, edges are clipped against a small near value:</p><pre>const NEAR_CLIP = 0.1</pre><p>If one vertex is in front of the plane and the other behind, I interpolate a new point exactly on the plane.</p><p>This prevents:</p><p>- infinite projection<br>- exploding geometry<br>- flickering artifacts</p><p>This is one of those small details that make the engine feel “real”.</p><h3>Step 6: Rendering Loop</h3><p>The entire animation is just:</p><pre>const render = () =&gt; {<br>  clearBuffer()<br>  const transformed = transformModel(model)<br>  renderModel(transformed)<br>  flushBuffer(container)<br>  requestAnimationFrame(render)<br>}</pre><p>That’s the whole loop.</p><p>No GPU.<br> No WebGL context.<br> Just math -&gt; buffer -&gt; text.</p><h3>What This Project Taught Me</h3><ol><li>3D is not magic.</li><li>Perspective is just division.</li><li>Rotation is just trigonometry.</li><li>Depth buffering is just an array comparison.</li><li>A “3D engine” can fit in a few hundred lines of code.</li></ol><p>The complexity of modern graphics engines hides how simple the foundations are.</p><p>Once you implement projection and rotation yourself, 3D stops being scary.</p><p>That’s it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dd8fc294ac5" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/creating-3d-text-engine-in-the-browser-7dd8fc294ac5">Creating 3D text engine in the browser</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[Staga — Orchestrating Resilient Async Workflows Without the Boilerplate]]></title>
            <link>https://medium.com/@sasha.kub95/staga-orchestrating-resilient-async-workflows-without-the-boilerplate-87d204f5bb3e?source=rss-6835a67ac4ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/87d204f5bb3e</guid>
            <category><![CDATA[saga]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Aleksandr Kubarskii]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 15:28:30 GMT</pubDate>
            <atom:updated>2025-08-08T15:30:44.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*YVysMBBr5zRNI3Hn.png" /></figure><h3>Redux is Dead. Staga — Orchestrating Resilient Async Workflows Without the Boilerplate</h3><p>We’ve all been there. You’re building a feature that looks simple enough:</p><ul><li>Provision a new user.</li><li>Spin up cloud resources.</li><li>Save some initial state.</li><li>Notify other services.</li><li>Confirm to the UI that it’s done.</li></ul><p>Then reality happens.</p><p>One of those steps fails. Another hangs. Your state is now half-updated, your logs are a mess, and you’re sifting through ad-hoc try/catch blocks wondering which pieces actually committed.</p><p>Modern apps are full of these <strong>multi-step flows</strong> — and they are surprisingly tricky to get right without building a small framework each time.</p><p><a href="https://github.com/kubarskii/staga"><strong>Staga</strong></a> is that framework. It treats these flows as <strong>first-class transactions</strong>: ordered steps that can be synchronous or asynchronous, with built-in <strong>retries, timeouts, cancellation, rollback, and reactive state</strong>.</p><h3>The Problem: Async Complexity Hides in Plain Sight</h3><p>Imagine you’re writing a “create account” flow. In code, it might look something like:</p><pre>async function createAccount(userData) {<br>  await saveUser(userData);<br>  await sendWelcomeEmail(userData.email);<br>  await provisionWorkspace(userData.id);<br>}</pre><p>It’s clean… until sendWelcomeEmail fails. Now you have a user in your database, but no workspace, and no notification sent.<br> Multiply this by dozens of flows across your app, each with its own quirks, and you’ve got a minefield of partial state.</p><p>You could scatter retry logic, cancellation flags, and compensating code (deleteUser, rollbackWorkspace) all over the place. But that’s fragile, hard to test, and easy to forget.</p><h3>The Staga Approach: Transactions With Compensation</h3><p>Staga borrows from the <strong>saga pattern</strong> in distributed systems:</p><p>A long-lived transaction is split into <strong>steps</strong>, each with:</p><ul><li>A <strong>main handler</strong> (do the work)</li><li>An optional <strong>compensation handler</strong> (undo the work)</li></ul><p>In Staga, a transaction might look like:</p><pre>import { createStore, transaction } from &#39;staga&#39;;<br>const store = createStore({ user: null, workspace: null });<br>const createAccount = transaction(store, &#39;createAccount&#39;, [<br>  {<br>    name: &#39;saveUser&#39;,<br>    run: (state, userData) =&gt; { state.user = userData; },<br>    compensate: (state) =&gt; { state.user = null; }<br>  },<br>  {<br>    name: &#39;sendWelcomeEmail&#39;,<br>    run: async (_, { email }) =&gt; { await emailService.send(email); },<br>    // no compensation needed<br>  },<br>  {<br>    name: &#39;provisionWorkspace&#39;,<br>    run: async (state, { id }) =&gt; {<br>      state.workspace = await workspaceService.create(id);<br>    },<br>    compensate: async (state) =&gt; {<br>      await workspaceService.delete(state.workspace.id);<br>      state.workspace = null;<br>    }<br>  }<br>]);</pre><p>Run it with:</p><pre>await createAccount.run({ id: 1, email: &#39;user@example.com&#39; });</pre><p>If any step fails:</p><ol><li>Staga <strong>reverses</strong> through completed steps.</li><li>Calls their <strong>compensation handlers</strong>.</li><li>Restores the store to its pre-transaction snapshot.</li></ol><p>The result? Your state is never left in a “half-done” mess.</p><h3>Reactive State That Doesn’t Lie</h3><p>Staga ships with a tiny <strong>reactive core</strong> — think of it as a minimal state manager with:</p><ul><li><strong>Proxy-based change tracking</strong></li><li><strong>Precise update notifications</strong></li><li><strong>Derived selectors that stay in sync</strong></li></ul><p>Why does this matter?<br> Because when a transaction runs, state changes are pushed to subscribers in real time. If something fails, rollback <strong>immediately</strong> resets the state and all selectors reflect the correct, safe value.</p><p>No ghost data. No stale computed values. Your state is <em>honest</em>.</p><h3>Guardrails: Timeouts, Retries, and Cancellation</h3><p>Real-world steps fail in messy ways:</p><ul><li>An API times out.</li><li>A database query hangs.</li><li>A network call randomly fails on the first try but works on the second.</li></ul><p>Staga bakes in:</p><ul><li><strong>Retries</strong>: Automatically re-run transiently failing steps.</li><li><strong>Timeouts</strong>: Abort a step if it takes too long.</li><li><strong>Cancellation</strong>: Stop a transaction mid-flight if upstream logic says “never mind”.</li></ul><p>Example:</p><pre>{<br>  name: &#39;fetchReport&#39;,<br>  run: async () =&gt; await reportService.get(),<br>  retries: 3,<br>  timeout: 5000<br>}</pre><h3>Middleware and Plugins: Cross-Cutting Without Pollution</h3><p>In a real app, you don’t just run workflows — you <strong>observe</strong> them, log them, measure them, persist them.</p><p>Staga’s middleware wraps transactions, and its plugin system provides lifecycle hooks like:</p><ul><li>install / initialize</li><li>beforeTransaction</li><li>afterTransaction</li><li>onStateChange</li></ul><p>Example logging middleware:</p><pre>store.useMiddleware(async (next, ctx) =&gt; {<br>  console.log(`Starting ${ctx.transactionName}`);<br>  await next();<br>  console.log(`Finished ${ctx.transactionName}`);<br>});</pre><p>This keeps <strong>cross-cutting concerns</strong> out of your business logic.</p><h3>Record and Replay: Deterministic Debugging</h3><p>Debugging async orchestration is notoriously painful. Logs help, but they can’t replay the actual state transitions.</p><p>Staga can:</p><ol><li>Record state changes and transaction events.</li><li>Replay them deterministically.</li></ol><p>That means you can step through exactly what happened in a failed run — perfect for:</p><ul><li>Reproducing bugs.</li><li>Making integration tests reliable.</li><li>Showing rollback behavior in demos.</li></ul><h3>TypeScript-First Design</h3><p>The API is intentionally small and strongly typed:</p><ul><li><strong>State</strong> is generic and typed at creation.</li><li>Steps get typed access to state and payload.</li><li>Both sync and async steps are supported without ceremony.</li></ul><pre>type State = { counter: number };<br>const store = createStore&lt;State&gt;({ counter: 0 });</pre><p>From there, TS gives you autocompletion and compile-time safety across transactions.</p><h3>Real-World Use Cases</h3><p>You might reach for Staga when:</p><ul><li><strong>Checkout flows</strong>: Payment, inventory update, confirmation — all atomic.</li><li><strong>Provisioning pipelines</strong>: Cloud resources and configs with rollback.</li><li><strong>Data migrations</strong>: Safe retries and undo if a batch fails mid-way.</li><li><strong>UI wizards</strong>: Multi-step forms where partial saves must be consistent.</li><li><strong>Background jobs</strong>: Tool orchestration with clear compensation.</li></ul><h3>How It’s Different From Other Tools</h3><ul><li><strong>State managers</strong> (Redux, Zustand) give reactivity but no built-in rollback.</li><li><strong>Workflow engines</strong> (Temporal, BullMQ) handle orchestration but not local reactive state.</li><li><strong>Custom sagas</strong> often end up verbose and inconsistent.</li></ul><p>Staga combines these pieces into one <strong>lightweight, framework-agnostic</strong> library that you can drop into browser or Node environments.</p><h3>Getting Started</h3><p>Install:</p><pre>npm install staga</pre><p>Create a store:</p><pre>import { createStore } from &#39;staga&#39;;<br>const store = createStore({ count: 0 });</pre><p>Define a transaction:</p><pre>const incrementTwice = transaction(store, &#39;incTwice&#39;, [<br>  { name: &#39;inc1&#39;, run: (state) =&gt; { state.count += 1; } },<br>  { name: &#39;inc2&#39;, run: (state) =&gt; { state.count += 1; } }<br>]);</pre><p>Run it:</p><pre>await incrementTwice.run();<br>console.log(store.getState().count); // 2</pre><h3>The Payoff</h3><p>Once you start modeling your flows as transactions, you:</p><ul><li>Gain <strong>atomicity</strong>: Either all steps commit, or none do.</li><li>Keep state <strong>honest</strong>: Rollback restores snapshots.</li><li>Simplify <strong>error handling</strong>: No more scattered try/catch soup.</li><li>Improve <strong>testability</strong>: Record/replay makes debugging sane.</li></ul><p>And you do it without dragging in a heavyweight workflow engine or writing thousands of lines of glue code.</p><p><strong>🔗 GitHub:</strong> <a href="https://github.com/kubarskii/staga">staga</a><br><strong>🔗 NPM:</strong> <a href="https://www.npmjs.com/package/@staga/core">staga</a></p><p>Let me know your opinion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87d204f5bb3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 minutes to create Rick and Morty search engine!]]></title>
            <link>https://medium.com/@sasha.kub95/10-minutes-to-create-rick-and-morty-search-engine-9f19bd9c949d?source=rss-6835a67ac4ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f19bd9c949d</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[search-engines]]></category>
            <dc:creator><![CDATA[Aleksandr Kubarskii]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 12:11:44 GMT</pubDate>
            <atom:updated>2024-07-19T15:39:09.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yRn9D-bTgJ5ST0OOqQd8g.png" /></figure><p>Search functionality plays a crucial role in improving user experience and engagement within digital platforms. It provides fast and accurate access to information. This capability is especially important in environments where time and accuracy are critical, such as academic research, customer service portals, e-commerce platforms, and the recently adopted technologies like RAG and chatbots. Effective search tools not only reduce the time users spend searching for specific information but also enhance the user experience by making interactions with the platform smoother and clearer. As users expect immediate results, seamless integration of advanced detection technologies becomes essential for any service that deals with large volumes of data. This ensures fast data retrieval, creating a better experience on the platform and encouraging reuse and deeper exploration of available resources.</p><p>In this article, we’ll implement our own search application with minimal effort. We’ll use some JavaScript, but the programming language is not crucial. We’ll also use <strong>Inquir</strong>, a super convenient Search as a Service application, that can index your data flexibly and expose an API to make search requests. As mentioned above, <strong>Inquir</strong> is a powerful search solution that makes it easy to create search engines, to support RAG systems, product discovery for e-commerce websites, scientific research, chatbots, and regular keyword search functionality.</p><h3>Preparations and Data acquisition</h3><p>We’ll be building an application to search Rick and Morty characters. To do this, we can use the public API for Rick and Morty ( <a href="https://rickandmortyapi.com/">https://rickandmortyapi.com/</a>). This API does not support search functionality out of the box, but with Inquir, we can index the entire API and search across it. Let’s go step by step and make all the necessary preparations to implement the Rick and Morty character search.</p><p>The <strong>Inquir</strong> configuration consists of the following parts:</p><ol><li>Create a Cluster</li><li>Create an Index by providing REST API Scraping config</li><li>Create an API Key for data access</li></ol><p>Let’s take a deep look into each of these steps. The first thing is the cluster.</p><p>In general, a <strong><em>cluster</em></strong> is an isolated instance of a search engine. As each cluster is isolated, you can restrict access independently to each data source and use a particular one in different applications. You can try to restrict data access on the index level, but clusters allow you to split access almost at the hardware level.</p><p>To create a cluster, go to the <strong>Inquir</strong> dashboard, then select <strong>Clusters</strong> link in the sidebar, then click on <em>Add Cluster</em> and provide the name you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n8VOvTU1rlycMDur" /></figure><p>Cluster creation can take up to 15 minutes because it requires infrastructure deployment. This is one of the advantages <strong>Inquir</strong> offers. You can always manually control the number of clusters you have and split loads if you have many apps and integrations.</p><p>Next, an <strong><em>index</em></strong> is a collection of documents with similar characteristics. It’s similar to a database in the traditional sense, where an index is analogous to a database table. Each document within an index is a basic unit of information that can be indexed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4sQFoYNFIDVlo5cm" /></figure><p>To create an index, click on the actions icon in the clusters table and select “Add source.” This will open a form where you can choose the type of source you want to add. As mentioned earlier, we are adding data from a REST API, so the Generic REST API Source is the most suitable for us. Inquir also supports scraping data from YouTube subtitles, sites by Sitemap, or simple URLs. If you want to push your data manually, you can use the Empty Source and add data manually using the <strong>Inquir</strong> PUSH API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FfPK36oeQ-ZMUTvw" /></figure><p>Clicking on Generic REST API, you are redirected to the next step, where it is needed to provide index name, scrapping configuration and optional flag <em>Enable context search.</em> For our purposes the flag can be left unchecked, but it’s up to you. As mentioned above, we’ll be scrapping and indexing Rick and Morty REST API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K8OJS775uWkHIv6E" /></figure><p>Scraping config is the most complicated part of this form. It maps REST API responses to a more understandable structure for <strong>Inquir</strong>, while still maintaining flexibility. The REST scraping config provisioning form has built-in suggestions, making it easier to update the configuration. For more details and config options, you can also check the <a href="https://inquir.org/docs">Inquir documentation</a> or event send an email to <a href="/service/mailto:info@inquir.org">info@inquir.org</a> to request a demo.</p><p>The scraping config used in the example is presented below.</p><pre>[<br>  {<br>    &quot;url&quot;: &quot;&lt;https://rickandmortyapi.com/api&gt;&quot;,<br>    &quot;endpoints&quot;: [<br>      {<br>        &quot;queryParameters&quot;: {<br>          &quot;page&quot;: 0<br>        },<br>        &quot;path&quot;: &quot;/character&quot;,<br>        &quot;method&quot;: &quot;GET&quot;,<br>        &quot;dataPath&quot;: &quot;results&quot;,<br>        &quot;uri&quot;: &quot;%[url]&quot;,<br>        &quot;title&quot;: &quot;%[name]&quot;,<br>        &quot;clickUri&quot;: &quot;%[url]&quot;,<br>        &quot;itemType&quot;: &quot;character&quot;,<br>        &quot;metadata&quot;: {<br>          &quot;character&quot;: &quot;%[INQUIR_RAW]&quot;<br>        }<br>      }<br>    ],<br>    &quot;pagination&quot;: {<br>      &quot;offsetType&quot;: &quot;page&quot;,<br>      &quot;parameters&quot;: {<br>        &quot;page&quot;: &quot;page&quot;<br>      },<br>      &quot;pageSize&quot;: 20,<br>      &quot;offsetStart&quot;: 1<br>    }<br>  }<br>]</pre><h3>Breakdown of the Configuration</h3><ol><li><strong>url</strong>: This is the base URL of the API from which data will be scraped. It serves as the starting point for all endpoint requests defined within the configuration.</li><li><strong>endpoints</strong>: Here, you define the specific parts of the API to interact with. Each item in the array is a specific endpoint configuration. Lets analyze <strong>endpoints object.</strong></li></ol><ul><li>path: This specifies the particular path of the API that the scraper should target. In this case, it’s the character endpoint, which provides data about characters in “Rick and Morty”.</li><li>method: This indicates the HTTP method used to access the API. GET is used here to retrieve data.</li><li>queryParameters: Here, you can define what query parameters to include in the API request. For instance, &quot;page&quot;: 0 is used to navigate through paginated results.</li><li>dataPath: This tells the scraper where in the API response to find the actual data. It is essential for navigating nested responses.</li><li>uri: A template that might be replaced by actual URL data, allowing dynamic request modifications.</li><li>title: Specifies how to label or title the data in the UI or logs, usually pulled dynamically from the data.</li><li>clickUri: Often used for interactive elements where a user might click to see more details, navigating using the URL provided by the data.</li><li>itemType: Defines the type of item, useful for categorization or processing logic in the scraper or consuming application.</li><li>metadata: Custom metadata that can be added to the scraped data. &quot;character&quot;: &quot;%[INQUIR_RAW]&quot; suggests adding raw data from the query to the &#39;character&#39; metadata field.</li></ul><p><strong>3. pagination</strong>: Handles how pagination is managed in API requests to ensure that all data can be fetched, particularly when data sets are large. It has the following parameters:</p><ul><li>offsetType: Specifies the method of pagination, here using page numbers.</li><li>parameters: Defines the query parameters for pagination, e.g., &quot;page&quot;: &quot;page&quot;.</li><li>pageSize: Indicates the number of items per page.</li><li>offsetStart: Tells where to start paging (useful for APIs where pagination starts at 1 instead of 0).</li></ul><p>After indexing is finished, or even during indexing, you can go to the <strong>Preview</strong> section to see how the data looks. You can check the preview in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SoPfknS8t5yd4RM-" /></figure><p>The last thing is API Keys. It makes it possible to issue tokens to access indices inside clusters. One API Key can be assigned only to one cluster. To issue one, go to API Keys → Add Key → Select created cluster → Create. In a second the API Key would be issued. Now we are ready for integrations.</p><h3>Building simple UI and Integrations</h3><p>Let’s first create a basic layout for the search input. It only contains a simple form element with one input and a submit button. I have also applied some CSS, and as a result, it looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I1lUYAiHT5ag9sXz" /></figure><p>The html for this can be found below.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Rick and Morty Search&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;form id=&quot;search-form&quot;&gt;<br>        &lt;input type=&quot;text&quot; id=&quot;search-input&quot; placeholder=&quot;Search Rick and Morty characters&quot;&gt;<br>        &lt;button type=&quot;submit&quot; id=&quot;search-button&quot;&gt;Search&lt;/button&gt;<br>    &lt;/form&gt;<br>    &lt;div id=&quot;results&quot;&gt;&lt;/div&gt;<br>    &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Next comes the JavaScript, which I can split into several parts. Let’s go through it step by step.</p><ol><li><strong>Setting Up the Event Form Listener</strong></li></ol><p>The code below attaches an event listener to the searchForm element. The listener is set up to react to the &quot;submit&quot; event, which is triggered when the user submits the form. This can happen when the user presses Enter while in the input field or clicks a submit button associated with the form.</p><pre>const searchForm = document.getElementById(&#39;search-form&#39;);<br>const searchInput = document.getElementById(&#39;search-input&#39;);<br>searchForm.addEventListener(&#39;submit&#39;, function (event) {<br>  event.preventDefault();<br>  performSearch(searchInput.value);<br>});</pre><p><strong>2. Fetching Data from the API</strong></p><p>The getResultss function handles the API interaction using the Fetch API to send requests. An AbortController is used to cancel previous requests if a new one is made, preventing overlapping responses. Pay attention to body, which is the search payload and the url used for integration <a href="https://platgorm.inquir.org/">https://platgorm.inquir.org</a>. Check the <a href="https://inquir.org/docs">docs</a> out for more configuration parameters.</p><p>The getResultss function handles the API interaction using the Fetch API to send requests. An AbortController is used to cancel previous requests if a new one is made, preventing overlapping responses. Pay attention to body, which is the search payload and the url used for integration <a href="https://platgorm.inquir.org/">https://platgorm.inquir.org</a>. Check the <a href="https://inquir.org/docs">docs</a> out for more configuration parameters.</p><ul><li>q: The query, a regular string</li><li>indexName: The index where you want to search for documents. This is optional; if omitted, the search will be done across all indices in the cluster.</li><li>size: The page size, preferably set to 12</li><li>page: The current page, starting from 1</li><li>ignoreMetadata: A special flag that removes redundant fields from the search, as I prefer searching by title for this specific API.</li></ul><p>I also suggest referring to the Inquir docs to learn more about its API.</p><pre>let abortController = new AbortController();<br>const SIZE = 12;<br>const getResults = async (q, page = 1) =&gt; {<br>  abortController.abort();<br>  abortController = new AbortController();<br>  const body = {<br>    q: q ?? &quot;&quot;,<br>    indexName: &quot;rnm2&quot;,<br>    size: SIZE,<br>    page,<br>    ignoreMetadata: true,<br>  };<br>  <br>  try {<br>    const response = await fetch(`https://platform.inquir.org/api/v1/search/query`, {<br>      signal: abortController.signal,<br>      headers: {<br>        &quot;Authorization&quot;: `Bearer &lt;YOUR API KEY HERE&gt;`,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;<br>      },<br>      method: &#39;POST&#39;,<br>      body: JSON.stringify(body),<br>    });<br>    <br>    return response.ok ? await response.json() : {};<br>  } catch (error) {<br>    console.error(&#39;Fetch error:&#39;, error);<br>    return {};<br>  }<br>};</pre><p><strong>3. Rendering Results</strong></p><p>After fetching data, the renderResults function takes over, parsing the API response and dynamically creating HTML elements to display each character&#39;s details. This ensures users see up-to-date results each time they search.</p><pre>function renderResults(data) {<br>  const resultsContainer = document.getElementById(&#39;results&#39;);<br>  resultsContainer.innerHTML = &#39;&#39;; // Clear previous results<br>  if (data.results.length &gt; 0) {<br>    data.results.forEach(item =&gt; {<br>      const character = item.metadata.character;<br>      const itemElement = document.createElement(&#39;div&#39;);<br>      itemElement.className = &#39;result-item&#39;;<br>      itemElement.innerHTML = `<br>        &lt;div class=&quot;character-card&quot;&gt;<br>        &lt;img src=&quot;${character.image}&quot; alt=&quot;${character.name}&quot; class=&quot;character-image&quot;&gt;<br>        &lt;div class=&quot;character-info&quot;&gt;<br>        &lt;h4&gt;${character.name}&lt;/h4&gt;<br>        &lt;p&gt;&lt;strong&gt;Species:&lt;/strong&gt; ${character.species}&lt;/p&gt;<br>        &lt;p&gt;&lt;strong&gt;Status:&lt;/strong&gt; ${character.status}&lt;/p&gt;<br>        &lt;p&gt;&lt;strong&gt;Gender:&lt;/strong&gt; ${character.gender}&lt;/p&gt;<br>        &lt;p&gt;&lt;strong&gt;Location:&lt;/strong&gt; ${character.location.name}&lt;/p&gt;<br>        &lt;a href=&quot;${character.url}&quot; target=&quot;_blank&quot;&gt;View Profile&lt;/a&gt;<br>        &lt;/div&gt;<br>        &lt;/div&gt;<br>      `;<br>      resultsContainer.appendChild(itemElement);<br>    });<br>  } else {<br>    resultsContainer.innerHTML = &#39;&lt;p&gt;No characters found. Try another search!&lt;/p&gt;&#39;;<br>  }<br>}</pre><p>As a result we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vP8EvoHloYRZDlUI" /></figure><h3>Summary</h3><p>This guide demonstrates the simplicity and efficiency of setting up a search application with Inquir. By turning the Rick and Morty API into a searchable dataset, we provide a template for similar implementations across various sectors, highlighting the potential to significantly enhance data accessibility and user engagement.</p><h3>References</h3><p>Check the demo: <a href="https://codepen.io/nenecmrf/pen/bGPEKNz">codePen</a></p><p>Check out Inquir: <a href="https://inquir.org/">Inquir</a></p><p>Read more in Inquir docs: <a href="https://inquir/docs">Inquir docs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f19bd9c949d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This is how you should calculate Fibonacci in JavaScript! To 1 million and above.]]></title>
            <link>https://medium.com/@sasha.kub95/this-is-how-you-should-calculate-fibonacci-in-javascript-966fe6684daa?source=rss-6835a67ac4ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/966fe6684daa</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fibonacci]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Aleksandr Kubarskii]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 09:48:46 GMT</pubDate>
            <atom:updated>2024-04-25T10:05:42.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*CH_77E3MIhxsTO8l" /></figure><p>I believe many people are asked how to create a function that calculates Fibonacci numbers during interviews. Just to remind you, it’s a sequence of numbers where the next number is equal to the sum of the two previous ones, and it starts with two leading “1s,” like this:</p><p>1,1,2,3,5,8,13,21,34…</p><p>This sequence, though simple in appearance, pops up in various areas of mathematics, art, nature, and even computer science. In this article, I’ll delve into several ways to compute Fibonacci numbers using different programming approaches. Whether you’re preparing for a job interview or simply curious about this fascinating numerical sequence, understanding how to efficiently calculate Fibonacci numbers can be both a fun challenge and a useful skill. Let’s explore some common and some not-so-common methods, evaluate their performance, and discuss where you might encounter this sequence in real-world applications.</p><h3>Recursive Approach</h3><p>One of the most straightforward methods to compute Fibonacci numbers is through recursion. This approach directly stems from the definition of the Fibonacci sequence: each number is the sum of the two preceding ones.</p><h4>The Code</h4><p>Here’s how you can implement it in JavaScript:</p><pre>const fibonacci = (n) =&gt; {<br>  if (n &lt;= 1) {<br>      return n<br>  }<br>  else {<br>      return fibonacci(n-1) + fibonacci(n-2)<br>  }<br>}</pre><h4>How It Works</h4><p>The function fibonacci takes an integer n as input and returns the n-th Fibonacci number. The function checks if n is 0 or 1, in which case it returns n directly since the first two Fibonacci numbers are 0 and 1, respectively. For all other values of n, the function calls itself twice: once for fibonacci(n-1) and once for fibonacci(n-2), adding the results of these two calls to get the n-th Fibonacci number.</p><h4>Analysis</h4><p>While recursive solutions are elegant and easy to understand, they are not the most efficient. This particular implementation has an exponential time complexity, specifically O(2^n), due to the repeated recalculations of the same Fibonacci numbers. As n increases, the number of function calls grows exponentially, leading to significant slowdowns for large n.</p><h4>Benchmark</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*xJYiHqmKI-spVhS1PVhs7w.png" /></figure><p>This performance issue illustrates a common problem in recursive algorithms known as overlapping subproblems. In the next section, we will explore how to address this inefficiency by introducing dynamic programming principles.</p><h3>Dynamic Programming</h3><p>At first, let’s check what dynamic programming is. Dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems and solving each of these subproblems just once, storing their solutions. The idea is to use these stored solutions directly, reducing the number of calculations needed to solve the same problem as it recurs in various forms throughout the algorithm. This technique is particularly useful for problems that exhibit the properties of overlapping subproblems and optimal substructure, meaning that the solution to a problem can be constructed from solutions to its subproblems. Dynamic programming can be implemented in various ways, such as top-down with memoization or bottom-up, which builds up solutions to larger and larger subproblems from the smallest ones.</p><p>To overcome the inefficiencies of the simple recursive approach, we can employ dynamic programming with memoization. This technique involves storing the results of expensive function calls and reusing them when the same inputs occur again. This avoids the need for recalculating the results of previously computed Fibonacci numbers, which is a significant drawback in the naive recursive approach. By leveraging the strengths of dynamic programming, we not only enhance performance but also increase the scalability of our solution to handle larger inputs effectively.</p><h4>The Code</h4><p>Here’s an implementation in JavaScript using an immediately invoked function expression (IIFE) that returns a memoized version of the Fibonacci function:</p><pre>const fib = (() =&gt; {<br>  const cache = {};<br>  return (n) =&gt; {<br>    if (!!cache[n]) {<br>      return cache[n];<br>    }<br>    if (n &lt;= 1) {<br>      return cache[n] = BigInt(n);<br>    } else {<br>      return cache[n] = fib(n - 1) + fib(n - 2);<br>    }<br>  };<br>})();</pre><h4>How It Works</h4><p>This function uses an object, cache, to store previously computed Fibonacci numbers. The function fib checks if the result for a given n is already in the cache. If it is, it returns that value, which cuts down on the number of calculations dramatically.</p><ul><li>Cache check: If fib(n) has been called before, the result is already in the cache, and we can return it immediately.</li><li>Base cases: If n is 0 or 1, we store and return BigInt(n) to handle large numbers gracefully.</li><li>Recursive calculation: If n is greater than 1 and not in the cache, we compute it by recursively calling fib(n - 1) and fib(n - 2) and store the result in the cache.</li></ul><h4>Analysis</h4><p>This memoized recursive approach significantly improves the efficiency of computing Fibonacci numbers. The time complexity is reduced to O(n) because each Fibonacci number from 0 to n is calculated exactly once. This makes it vastly superior to the pure recursive solution for larger values of n.</p><p>Additionally, using BigInt allows us to handle very large numbers that exceed the safe integer limit in JavaScript, making our function robust for a wide range of inputs.</p><p>Here’s another benchmark but with dynamic programming approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*XxTQsJwuG8dxeqrTr0wiLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rzt96iHzVOueJpoBV5tvbg.png" /></figure><p>The difference is crazy!!!</p><h3>Iterative Approach</h3><p>The iterative approach is another way to computing Fibonacci numbers is straightforward and efficient. Instead of recursive calls, we use a loop to compute each number in the sequence up to the desired position.</p><h4>The Code</h4><p>Here’s how you can implement the iterative approach in JavaScript:</p><pre>function fibonacciIterative(n) {<br>    let a = BigInt(0), b = BigInt(1), c = BigInt(1);<br>    for (let i = 2; i &lt;= n; i++) {<br>        c = a + b;<br>        a = b;<br>        b = c;<br>    }<br>    return c;<br>}</pre><h4>How It Works</h4><p>This function initializes three variables: a, b, and c, which represent the two previous Fibonacci numbers and the current Fibonacci number, respectively. Starting from the third Fibonacci number (since the first two are 0 and 1):</p><ul><li>It iterates from 2 up to n.</li><li>In each iteration, it updates c to be the sum of a and b (the last two Fibonacci numbers).</li><li>It then shifts a to b and b to c to move forward in the sequence.</li></ul><p>By the end of the loop, c contains the nth Fibonacci number.</p><h4>Analysis</h4><p>The iterative approach has a time complexity of O(n), which is significantly more efficient than the simple recursive approach. It avoids the overhead of recursive function calls and the potential stack overflow issues associated with deep recursion. This method also uses a constant amount of space, making it space-efficient.</p><h4>Benchmark</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcNnmgHr7_BztNC5lyarkw.png" /></figure><h3>Matrix Exponentiation Approach</h3><p>Matrix exponentiation allows us to compute Fibonacci numbers in O(log n) time, making it one of the fastest algorithms for this problem. The approach is based on the fact that Fibonacci numbers can be represented as the result of multiplying a specific matrix raised to the power of <em>n</em>.</p><h4>The Code</h4><p>Here’s how you can implement the matrix exponentiation approach in JavaScript:</p><pre>function fib(n) {<br>    if (n &lt;= 1) return BigInt(n);<br>    const matrixPower = (matrix, n) =&gt; {<br>        let result = [[BigInt(1), BigInt(0)], [BigInt(0), BigInt(1)]];<br>        let base = matrix;<br>        while (n &gt; 0) {<br>            if (n % 2 === 1) {<br>                result = multiplyMatrices(result, base);<br>            }<br>            base = multiplyMatrices(base, base);<br>            n = Math.floor(n / 2);<br>        }<br>        return result;<br>    };<br>    const multiplyMatrices = (a, b) =&gt; {<br>        return [[<br>                a[0][0] * b[0][0] + a[0][1] * b[1][0],<br>                a[0][0] * b[0][1] + a[0][1] * b[1][1]<br>            ],<br>            [<br>                a[1][0] * b[0][0] + a[1][1] * b[1][0],<br>                a[1][0] * b[0][1] + a[1][1] * b[1][1]<br>        ]];<br>    };<br>    const F = [[BigInt(1), BigInt(1)], [BigInt(1), BigInt(0)]];<br>    const result = matrixPower(F, n - 1);<br>    return result[0][0];<br>}</pre><h4>How It Works</h4><p>This function uses a helper function matrixPower to raise a matrix to the nth power using exponentiation by squaring, which is efficient for large numbers. The multiplyMatrices function is used to perform matrix multiplication. The matrix F = [[1,1],[1,0]] raised to the power of <em>n</em>−1 gives us the Fibonacci sequence where the top left corner of the resulting matrix will be <em>F</em>(<em>n</em>).</p><h4>Analysis</h4><p>The matrix exponentiation method significantly reduces the time complexity to O(log n) because each matrix multiplication operation is constant time, and the number of multiplications grows logarithmically with n. This method is extremely fast and suitable for very large indices.</p><h4>Benchmark</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hTfznO2VyDgib7-eniyEWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*wQSrI4NB-tk2gxcTSHtTiQ.png" /></figure><p>In the end, I want to empower you to experiment and read about different algorithms. There’re many ways to solve common problems in much more efficient ways, but sometimes we have no idea that they even exist.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=966fe6684daa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Race conditions and Parallel programming in JavaScript?]]></title>
            <link>https://medium.com/@sasha.kub95/parallel-programming-in-javascript-830be90fbd3c?source=rss-6835a67ac4ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/830be90fbd3c</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[semaphore]]></category>
            <dc:creator><![CDATA[Aleksandr Kubarskii]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 17:29:22 GMT</pubDate>
            <atom:updated>2023-06-09T11:34:10.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttlIof2lRlNjVkx2lKns1g.png" /></figure><blockquote>At first, I should say that this article is just a heap of different technologies and approaches that i’ve tried to incorporate into one text. If you’re not afraid continue reading :).</blockquote><p>I belive almost everyone who’s working with JavaScript, espesially on frontend side has never really thought about parallel programming problems that we can really face with.</p><p>So at first, what does the term <em>parallel programming </em>means? <em>Parallel programing</em> or <em>parallel processing </em>is refered to the systems where tasks are parallelized in such a way, so that they can be run simultaniously using multiple cores within a CPU or even by using multiple computers. So, one can say that it’s not really about JavaScript, but at first in Node.js we have a bunch of methods how we can parallelize our task using worker threads, child processes or cluster and on UI side we have Web Workers. But in this article I won’t be touching the stuff described above because we can have familiar problems only by using Promises.</p><p>Lets try to simulate the parallel processing problem by implementing a simple blockchain using only Vanilla JavaScript <em>(Of cause I’m not gonna build the full centralised, decentralised or distributed network, just a simple app that is just a linked list with some extras)</em>.</p><p>Blockcahin is a pretty simple concept. Blockchain can be described as a linked list of signed objects (blocks). Signed means that the block can be added to the chain only after its hash was properly generated, for example it should contain the exact amount of zeros at the beginning. The process of generating such signed hash is usually called mining, and if you’re interested in blockcain technologies or cryptocurrency you may have also heard about Proof-of-Work (PoW), that is exactly the mining process. This description is very primitive, but can provide the basic understanding of what I’m planning to implement and why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*fouF4WxuLCL9jfdc.png" /><figcaption><a href="https://medium.com/mobindustry/designing-a-blockchain-architecture-types-use-cases-and-challenges-9894fb7b58e">https://medium.com/mobindustry/designing-a-blockchain-architecture-types-use-cases-and-challenges-9894fb7b58e</a></figcaption></figure><p>So as it was said blockchain consists of two main elements: Block and Chain. Lets start from the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*pGfONX8p22j4Mrx4w_8g3A.png" /><figcaption>Block Class</figcaption></figure><p>Block is a pretty simple thing, that contains several properties: <br>1. data — to store block data, it can be anything passed into the block;<br>2. hash — claculated hash of the Block;<br>3. prevHash — previous block in chain hash;<br>4. nonce — a utility variable that will help us to actually mine the hash by changing its value;<br>5. timestamp — the time of the object created.</p><p>Now few words about methods. There are only two of them, that are public: <strong><em>generateHash ()</em></strong>— that is responsible to generate hash based on data, nonce, timestamp and other stuff we want. In my case the hash will be generated also based on prevHash values, but it’s not so neccessary. And of course <strong><em>mine() </em></strong>method that will be generating hash until it’s a signed one (it should start with the exact amount of zeros).</p><p>It’s time for some coding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*MuTe86Ijrfi7Dl3P5HeIjg.png" /><figcaption>main part of <strong><em>generateHash()</em></strong> function</figcaption></figure><p>Before going deeper into the code, it should be mentioned that almost all methods created will be asyncronous, so it means that we’ll deal with promises. So lets move to the code. At a first glance, here we have a bit compicated code, so let consider it line by line. At first we should use TextEncoder. The TextEncoder interface takes a stream of code points as input and emits a stream of UTF-8 bytes. Next we call TextEncoder ‘s encode method to receive Uint8Array that will contain unsigned 8-bit integer values created from the data, prevHash and nonce that were provided. Phew… Lets go next! Actually we need this typed array to pass it into the next function that will generate a hash as it can only work with it. Next we call crypto.subtle.digest that receive hashing algorithm and typed array as parameters and returns the promise. The fulfilled promise will return ArrayBuffer. To actually pull the string out of this ArrayBuffer, we should first wrap it with typed array Uint8Arry and then we’ll be able to put its values into more common “usual” Array. But it’s not everything we need. Finally we convert the Array into string. And now the process of generating hash is finished. From this point, any time we call <strong><em>generateHash(), </em></strong>and do not change any parameters passed to hasing algorithm, we’ll always must receive the same hash.</p><p>Next step is to create <strong><em>mine()</em></strong> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*MFEGL7T5PCuVXLRIGiQo-w.png" /></figure><p>So the idea here is pretty simple. We recursivly execute the function untill we receive the hash we need. Each iteration we must update nonce to make <strong><em>generateHash() </em></strong>function return new value each time it’s called. When the hash is acceptable, it’s returned.</p><p>So these were the key points of Block implementation, now lets move to the Chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*Jdg0a5ycAm_UBUJgkv_G3w.png" /><figcaption>Chain Class</figcaption></figure><p>Chain is a simple entity with just several properties and one public method. The chain stores all chain block while difficulty will be used during mining process. <strong><em>Add() </em></strong>method is serves for adding new Blocks into the Chain. So lets go to the implementation now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*_7H3QlFF4o-5YJ3Dd52Blw.png" /><figcaption>add() method</figcaption></figure><p>So here we have a code that generates block’s hash by calling it’s <strong><em>mine() </em></strong>method. And after the hash was generated the block is pushed into the chain. Very straightforward, isn’t it? Yes, but here comes the problem. What if we add many blocks almost simultaniously. It will cause the problems with hash calculation. In this particular case we’re trying to get access to one shared resorce from many different places. That problem is actually very common in distributed systems and parallel programming as a result. And the solution for it also comes from parallel programming. The simplest option we have is to implement a Semaphore. Are you scared? But basically it’s really plain thing. Lets move.</p><blockquote>A<strong> semaphore</strong> is a signaling mechanism. … <em>. </em>Semaphores are used for synchronization (between tasks or between tasks and interrupts) and managing allocation and access to shared resources.<em> </em><a href="https://open4tech.com/rtos-mutex-and-semaphore-basics/">https://open4tech.com/rtos-mutex-and-semaphore-basics/</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*bw7KeEVHv5zsWeiY.jpg" /><figcaption>Semaphore architecture</figcaption></figure><p>Lets take a look at Semaphore implementation in JavaScript:</p><pre>export class Semaphore {<br>    _maxConcurrRequests<br>    runningRequests = 0<br>    requests = []<br>    <br>    constructor(concurrRequests = 1) {<br>        this._maxConcurrRequests = concurrRequests<br>    }<br>    <br>    $call(fn, ...args) {<br>        return new Promise((resolve, reject) =&gt; {<br>            this.requests.push({<br>                resolve,<br>                reject,<br>                fn,<br>                args<br>            })<br>            this.#next()<br>        })<br>    }<br>    <br>    #next() {<br>        if (!this.requests.length) {<br>            return;<br>        }<br><br>        if (this.runningRequests &lt; this._maxConcurrRequests) {<br>            let {resolve, reject, fn, args} = this.requests.shift();<br>            ++this.runningRequests;<br>            let req = fn(...args);<br>            req.then((res) =&gt; resolve(res))<br>                .catch((err) =&gt; reject(err))<br>                .finally(() =&gt; {<br>                    --this.runningRequests;<br>                    this.#next();<br>                });<br>        }<br>    }<br>}</pre><p>Actually semaphore logic is really close to the queue. We wait until the first (or several first) promise in requests Array is finished and then return the result and go to the next function to be executed. By applying such approch in blockchain we’ll block the ability to add new blocks untill the previous one is added and hash is calculated.</p><h3>Bonus</h3><p>The source code of the todo list based on blockchain can be found here:<br><a href="https://github.com/kubarskii/blockchain-todo">https://github.com/kubarskii/blockchain-todo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=830be90fbd3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency injection (DI) and DI Container with Vanilla JavaScript]]></title>
            <link>https://medium.com/@sasha.kub95/dependency-injection-di-and-di-container-with-vanilla-javascript-adb888498bd?source=rss-6835a67ac4ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/adb888498bd</guid>
            <category><![CDATA[loosecoupling]]></category>
            <category><![CDATA[vanillajs]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Aleksandr Kubarskii]]></dc:creator>
            <pubDate>Sun, 13 Mar 2022 17:12:15 GMT</pubDate>
            <atom:updated>2022-03-14T08:24:03.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="DI Container" src="https://cdn-images-1.medium.com/max/351/1*Ru14fJQjR_baD8GBsmY8jQ.png" /></figure><p>Only the lazy hasn’t written about dependency injection in JavaScript and now it’s my turn. The one said:</p><blockquote>What I cannot create, I do not understand. (<strong>Richard Feynman)</strong></blockquote><p>This is the main reason I’m writing this small article. The code or architecture provided below is probably far not good, as it was created spontaneously, and I don’t recommend to use it in production.</p><p>Before trying to understand what the dependency injection is, let’s consider the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*EO_rSlScAeIIRE10OPb_YQ.png" /></figure><p>Here we have <strong>Api</strong> class and <strong>Order</strong> class. To make the order, <strong>Order</strong> class creates <strong>Api</strong> instance. In this example class <strong>Order</strong> becomes closely related with <strong>Api</strong> or in other words the coupling is increasing.</p><p>So, what problems can occur when we use such approach? At first, we will have some problems with testing. We will have to find a way to mock <strong>Api </strong>methods or intercept them before the actual API request is made. Another thing is that <strong>Api </strong>class can be used in many different services, for e.g., we can have different services for orders, cart, user and so on, considering a simple online store. And what if we want to replace our <strong>Api </strong>class with another to switch from HTTP to WebSockets for e.g. In this case we’ll have to update each part of the code that uses the current <strong>Api </strong>class. It would be much better if we have a declarative configuration and just tell our classes what dependencies they should use and provide them to the classes. Exactly for this purpose and to solve the problems listed above we can use <strong><em>dependency injection</em></strong> and <strong><em>DI container</em></strong>.</p><p>So, the DI can help us to make classes independent from the creation of objects it depends on, can provide a declarative approach of describing dependencies between objects with configuration that can be separated to another file. It also provides ability to update this configuration easily on demand.</p><p>After we start using DI, our code may start looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*4UZHZyjIYQWAsdvq4jUrFg.png" /></figure><p>In this example Order class is receiving “<strong><em>Api”</em></strong> in constructor. The “<strong><em>Api”</em></strong> is an instance of <strong>Api </strong>class. In such approach instead of creating instance of the Api inside of <strong>Order</strong> class we’ve just passed it directly. Basically, it means that somewhere in the code we will have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*RqUD_ETiB3kI7KfXE0fb0w.png" /></figure><p>Actually, by using such approach we can solve almost all problems we have described in paragraphs above, but as the application continue growing it becomes more and more difficult to manually control instances creation and updating everything across the code. So to automate this stuff we can relate to DI Container.</p><p>Commonly DI Containers in JS are created in pair with TypeScript and reflect-metadata. These packages add extended syntax for interfaces declaration and provides additional metadata we need to understand what dependencies we need by analyzing interfaces of constructor parameters.</p><p>But I really wanted to make everything work without any external dependencies, so the way I found is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">Proxy</a>. Proxy is a really cool feature of JavaScript that helps as change the default behavior of the language. In our case we will be using it to change the construction behavior. We really need it to get the parameters of the constructed instance, and here how we can do it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*u8AFhlraPRgGehgcmlUb1w.png" /><figcaption>injectable decorator</figcaption></figure><p>Here we have <strong><em>injectable()</em></strong> function. This is the decorator function that we gonna be using to wrap our classes and intercept their construction. We do it with the Proxy. Proxy intercepts <strong><em>construct </em></strong>and adds the following logic to it: it simply parses class code and extracts all the constructor properties as a simple strings with <strong><em>getConstructorParams().</em></strong> It looks in such way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*EVrtbEw0614xih2_ChGBHw.png" /></figure><p>After getting all injected services name we can get the preregistered instances from the DI Container. As for the actual DI Container — it’s pretty straightforward. It receives the map of classes that can be injected or used as services and after it can be received from dependencies map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*We3l_GswTMtECigE07_8Ow.png" /></figure><p>The <strong>dependency(interfaces) </strong>method is responsible for creating and returning the instances of classes by interface names passed.</p><p>Now we can actually leverage everything we’ve created before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*WEqh-zSb3JTIPm2ZYMfkbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*mKap5ZFDyDy-_z8-ZOh1sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*EX0DED2Z5yNN8KpIxEualQ.png" /></figure><p>So here are several created classes. We created them by using injectable decorator as we need to override construct behavior.</p><p>Next we register them all within DI Container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*5z5k2iR40h9vPj69moM52Q.png" /></figure><p>And finally lets create <strong>Order </strong>instance and call <strong><em>makeOrder()</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*J-B4va4bDwUA7r8KJ2uN7Q.png" /></figure><p>This is the console output received:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kB6ATLh4E-2YIlfcnOOosw.png" /></figure><p>If we want to start using another service instead of HttpModule, we can simply replace it with another dependency in Container config like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*P_M_qbiG-IaeuDCtdyGDxg.png" /></figure><p>And when we execute our code we’ll get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*3z8d-lN5iOXOnb36N8DeEw.png" /></figure><p>So here, we have replaced HttpModule service to Http service in a second. Isn’t it great?! Of course this code is not great and to use it in production we’ll also have to add some checks to prevent cyclic dependencies, create singletons instead of new instances, make it possible to inject not only classes but functions, primitives and so on.</p><p>At the end I can say the DI is an incredibly cool pattern that can significantly improve your code. If you really want to use it in your projects try to consider Angular’s DI, typedi or many other packages created.</p><p>Thanks for reading!</p><p>You can find the source code here: <a href="https://github.com/nenecmrf/di">https://github.com/nenecmrf/di</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adb888498bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webcam stream to ascii art with JavaScript]]></title>
            <link>https://medium.com/@sasha.kub95/webcam-stream-to-ascii-art-with-javascript-2a2f9a39befb?source=rss-6835a67ac4ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a2f9a39befb</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ascii-art]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[html5]]></category>
            <dc:creator><![CDATA[Aleksandr Kubarskii]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 23:14:13 GMT</pubDate>
            <atom:updated>2022-05-12T19:31:18.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frJWk5bxjJp5NxeoouQGTw.png" /></figure><p>Not so long ago, when we didn’t have GUI, but only consoles, people used to create many cool applications and games using only ascii characters. I always liked this idea, but in todays world it’s not so useful, but we can still have a lot fun playing with ascii characters, trying to create something. I decided to follow this route and made video stream from the webcam available as ascii characters and it turned out to be pretty simple.</p><p><strong>What we’ll need</strong>: browser, vanilla JavaScript, Google, MDN<br><strong>What we’ll have to do</strong>: <br>1. Get video stream;<br>2. Get each pixel colors;<br>3. Convert color to grayscale;<br>4. Get ascii character based on color lightness;</p><p>Let’s go step by step.<br>At first we will need some basic <strong>&lt;html&gt;</strong> that we will be using to display ascii video stream.</p><pre>&lt;!doctype html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;title&gt;Ascii video stream&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;style&gt;<br>  body {<br>    background: #00005e<br>  }<br><br>  video, canvas {<br>    display: none;<br>  }<br><br>  #text-video {<br>    font-family: Courier, serif; // use it to make chars width equal<br>    font-size: 6px;<br>    line-height: 4px;<br>    color: white;<br>  }<br>&lt;/style&gt;<br><br>&lt;body&gt;<br>&lt;div&gt;<br>  &lt;div&gt;<br>    &lt;video id=&quot;video&quot;&gt;Video stream not available.&lt;/video&gt;<br>    &lt;canvas id=&quot;canvas-video&quot;&gt;&lt;/canvas&gt;<br>  &lt;/div&gt;<br>  &lt;div id=&quot;text-video&quot;&gt;&lt;/div&gt;<br>  &lt;button id=&quot;stop&quot;&gt;Stop&lt;/button&gt;<br>&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>This html is very simple and contains 3 important things: <strong>&lt;video&gt;</strong> to capture the video stream easily, <strong>&lt;canvas&gt;</strong> that will be used for displaying video and processing pixels and <strong>&lt;div id=”text-video”&gt; </strong>that will display ascii characters.</p><p>Now lets move to displaying video stream.</p><p>This is pretty simple and easy-to-do thing that can be done in several lines of code.</p><pre>const video = <strong><em>document</em></strong>.getElementById(&#39;video&#39;);</pre><pre>const initTextVideo = () =&gt; {<br>  <strong><em>navigator</em></strong>.mediaDevices.getUserMedia({ video: true, audio: false })<br>    .then(function (stream) {<br>      video.srcObject = stream;<br>      video.play();<br>    })<br>    .catch(function (err) {<br>      <strong><em>console</em></strong>.log(&quot;An error occurred: &quot; + err);<br>    });<br>}</pre><p>The <em>getUserMedia</em> method is used to get user media, depending on parameters provided, in our case we’ll use only video. You can read more about <em>getUserMedia </em><a href="https://developer.mozilla.org/en-US/docs/web/api/mediadevices/getusermedia">here</a>. According to MDN: “getUserMedia returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> that resolves to a <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaStream">MediaStream</a> object. If the user denies permission, or matching media is not available, then the promise is rejected with NotAllowedError or NotFoundError <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMException">DOMException</a> respectively.” After the promise is resolved we can set the <strong>&lt;video&gt;’s </strong>srcObject the stream returned by Promise and call the <strong>play()</strong> method that will attempt to begin playback of the media.</p><p>Now it’s time for the second step — to get pixels and process them.</p><p>At first lets draw the video stream to <strong>&lt;canvas&gt;.</strong></p><pre>const canvas = <strong><em>document</em></strong>.getElementById(&#39;canvas-video&#39;);<br>const ctx = canvas.getContext(&#39;2d&#39;);<br>const width = 320 / 2, height = 240 / 2;</pre><pre>const clearphoto = (ctx) =&gt; {<br>  ctx.fillStyle = &quot;#fff&quot;;<br>  ctx.fillRect(0, 0, width, height);<br>}<br><br>const render = (ctx) =&gt; {<br>  if (width &amp;&amp; height) {<br>    canvas.width = width; // setting canvas resolution<br>    canvas.height = height;<br>    ctx.drawImage(video, 0, 0, width, height);<br>  } else {<br>    clearphoto(ctx);<br>  }<br>}</pre><p>This is all we need to start drawing video on <strong>&lt;canvas&gt;. </strong>Simple, isn’t it? With this code. The main part here is <strong><em>ctx.drawImage(video, 0, 0, width, height). </em></strong>By this line we tell canvas to get video and draw it inside canvas.</p><p>Now we are coming to the most interesting part — converting pixels into ascii and drawing it.</p><pre>const gradient = &quot;_______.:!/r(l1Z4H9W8$@&quot;;<br>const preparedGradient = gradient.replaceAll(&#39;_&#39;, &#39;\u00A0&#39;)</pre><pre>const getPixelsGreyScale = (ctx) =&gt; {<br>  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);<br>  const data = imageData.data;<br>  let row = 0<br>  const res = new <strong><em>Array</em></strong>(height).fill(0).map(() =&gt; []);<br>  for (let i = 0, c = 0; i &lt; data.length; i += 4) {<br>    const avg = (data[i] + data[i + 1] + data[i + 2]) / 3;<br>    let curr = res[row]<br>    curr.push(avg)<br>    if (c &lt; width) {<br>      c++<br>    }<br>    if (c === width) {<br>      c = 0<br>      row += 1<br>    }<br><br>  }<br>  return res<br>}<br><br>const getCharByScale = (scale) =&gt; {<br>  const val = <strong><em>Math</em></strong>.floor(scale / 255 * (gradient.length - 1))<br>  return preparedGradient[val]<br>}<br><br>const renderText = (node, textDarkScale) =&gt; {<br>  let txt = `&lt;div&gt;`<br>  for (let i = 0; i &lt; textDarkScale.length; i++) {<br>    for (let k = 0; k &lt; textDarkScale[i].length; k++) {<br>      txt = `${txt}${getCharByScale(textDarkScale[i][k])}`<br>    }<br>    txt += `&lt;br&gt;`<br>  }<br>  txt += `&lt;/div&gt;`<br>  node.innerHTML = txt<br>}</pre><p>Here we have <strong><em>getPixelsGreyScale()</em></strong> function that actually does all the job. At first it takes “ImageData”, that is array, that contains RGBA values for each pixel on canvas. The structure is the following: [r, g ,b ,a ,r ,g ,b ,a ,….]. As you can see it’s a flat array and each 4 elements of it applies to 1 pixel. And the next thing we do in this function is turning rgba into one value (from 0 to 255) and also splitting flat array into “rows”.</p><p><strong><em>getCharByScale() </em></strong>is used to select ascii character from chars list based based on the color lightness. It’s simply normalizes value range 0–255 to 0-gradient.length.</p><p><strong><em>renderText()</em></strong> is event much simplier. We just take array of arrays of pixel lightness and by using <strong><em>getCharByScale() </em></strong>prepare html and insert it into the passed node.</p><p>One thing left — add infinite loop to render the characters.</p><pre>const interval = setInterval(() =&gt; {<br>  requestAnimationFrame(() =&gt; {<br>    render(ctx)<br>    const chars = getPixelsGreyScale(ctx)<br>    renderText(textVideo, chars)<br>  })<br>})</pre><p>That is all… You can check the gist with the example <a href="https://gist.github.com/kubarskii/5bf43f65799d858e6b612cc8b1f76d2a">here</a>.</p><p>P.S.</p><p>This is my first attempt to publish on medium. Interesting to know your opinion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a2f9a39befb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>