<?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 Yan Tsishko on Medium]]></title>
        <description><![CDATA[Stories by Yan Tsishko on Medium]]></description>
        <link>https://medium.com/@yantsishko?source=rss-d4d014fc538c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IcyWhjHio4AKXcUbCwb_Dg.jpeg</url>
            <title>Stories by Yan Tsishko on Medium</title>
            <link>https://medium.com/@yantsishko?source=rss-d4d014fc538c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:48:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yantsishko/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Relocated to the USA, Looked for Opportunities, Offers I Received from MAANG, and More]]></title>
            <link>https://javascript.plainenglish.io/how-i-relocated-to-the-usa-looked-for-opportunities-offers-i-received-from-maang-and-more-30e2cea7b99e?source=rss-d4d014fc538c------2</link>
            <guid isPermaLink="false">https://medium.com/p/30e2cea7b99e</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[maang]]></category>
            <category><![CDATA[interview-in-usa]]></category>
            <dc:creator><![CDATA[Yan Tsishko]]></dc:creator>
            <pubDate>Tue, 04 Oct 2022 09:16:24 GMT</pubDate>
            <atom:updated>2022-10-04T09:16:24.307Z</atom:updated>
            <content:encoded><![CDATA[<h4>The story of my relocation to the US, how I looked for opportunities, the offers I received here from Big-Tech companies, and more.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97G6DQc_ma57zdZAPbcGpQ.jpeg" /><figcaption>Photo krakenimages from Unsplash</figcaption></figure><p>In February 2022, I finally moved to the US on an O1 work visa. This was preceded by 2.5 years of work on strengthening the case, waiting for approval.</p><p>1.5 years before this date, I started preparing for an interview for a Front End position. Currently working as a Senior Front-End Engineer at Roku.</p><p>This post and the creation of the <a href="https://t.me/front_end_interview">Telegram channel</a> were motivated by the lack of detailed information about interviews for Front-End engineers in the USA.</p><h3>What I did before</h3><p>Before relocation, I worked for 7 years in outsourcing companies in Belarus. This allowed me to use different technologies, and approaches and work on various projects. Prior to relocating, I already held a position as an Engineering Manager with 26 JavaScript engineers (this strengthened my CV, especially for a Staff position). Over the past year, I have conducted about 50 technical interviews in the department.</p><p>But in the USA, I realized that my experience is not entirely relevant, and I need to start from a Senior position in order to figure out how the processes are built here, the culture, and how to conduct interviews, which are completely different here.</p><p>I started preparing for the technical interview 1.5 years in advance while I was waiting for my visa. Every morning of my working week was spent preparing. It became a habit over time and did not cause any discomfort. After a while, I was promoted to the Engineering Manager position as I was growing at a rapid rate.</p><h3>Preparation</h3><p><strong>1. Leetcode</strong></p><p>I solved 245 problems on Leetcode. I mostly focused on arrays, matrices, trees, linked lists, strings, hash tables, sorts, and two-pointers. In my <a href="https://leetcode.com/yantsishko/">profile</a>, you can see the topics that I solved.</p><p><a href="https://github.com/yantsishko/leetcode">Here</a> are all the tasks that I solved.</p><p>To familiarize and refresh data structures and algorithms in JS, I used the <a href="https://github.com/trekhleb/javascript-algorithms">javascript-algorithms</a> resource.</p><p>To quickly identify Leetcode problem patterns, read this article — <a href="https://hackernoon.com/14-patterns-to-ace-any-coding-interview-question-c5bb3357f6ed">14 Leetcode problem patterns</a>. It helps identify the problem.</p><p>To determine the complexity of the code, there is a <a href="https://www.bigocheatsheet.com/">cheat sheet</a> on Big O notation.</p><p>For examples of ​​what an interview looks like, I used the <a href="https://interviewing.io/recordings">interviewing</a> resource.</p><p><strong>2. Big Front End (</strong><a href="https://bigfrontend.dev/"><strong>https://bigfrontend.dev/</strong></a><strong>)</strong></p><p>I solved 50% of BFE problems (easy and medium). I published all these solutions on my <a href="https://t.me/front_end_interview">Telegram channel</a>. This resource is most useful for interviews at Meta, but other companies are more or less likely to ask similar questions.</p><p><strong>3. System design</strong></p><ul><li>To prepare for system design, I used <a href="https://youtube.com/playlist?list=PLI9W87-Dqn7j_x6QtR6sUjycJR7nQLBqT">Evgenii Ray’s</a> videos. He covered most aspects of systems design that I encountered in real interviews.</li><li>A very useful resource for system design and for real work (Web Performance) — <a href="https://3perf.com/talks/web-perf-101/">3perf</a>.</li><li>All about <a href="https://www.a11yproject.com/checklist/#content">accessibility</a>.</li></ul><p><strong>4. Behavioral interview</strong></p><ul><li><a href="https://www.notion.so/BE-Interview-8adc74cf14ad450fab3083e0633d2821">List of questions</a> for preparation and examples of answers.</li><li>For the mock interview, I used the <a href="https://t.me/FaangInterview">FAANG</a> telegram channel and <a href="https://www.pramp.com/">Pramp</a>.</li><li>I also used this <a href="https://t.me/frontend_engineer_blog">telegram channel </a>and <a href="https://www.notion.so/Front-End-Preparation-a0ac842415a04ddf9319718ea6ba22a4">Evgenii Ray’s Notion</a> and resolved everything from there, reading it all the way through.</li></ul><p>On glassdoor, you can find some examples of questions and tasks that companies ask.</p><h3>And finally, I’m in the USA</h3><p>Upon arrival, I had a 2-week jet lag, there was no way of passing the interview, and I could not sleep normally.</p><p>But after I adapted, I began to actively set up calls with recruiters, writing on LinkedIn. There were 20–30 messages with opportunities per day, but most of them are no-name companies or startups.</p><p>Before replying to the message, I analyzed the company, investments, whether it is a public or private company, what they do, and what technologies they work with (I basically focused on React, JS/TS stack, as well as the Front End position).</p><p>This was the original filter.</p><p>During the day I had 3–4 phone calls with recruiters, then 2 technical interviews.</p><p>In total, I participated in about 20 mocks to understand how to behave in an interview and what my weaknesses are, but this does not compare with real interviews. In real interviews, I already had a noticeable growth, already after 1–1.5 months, I began to solve problems more efficiently, find out requirements, sell myself and answer behavioral questions, because after each interview I did work on mistakes, and corrected stories.</p><p>I started with small startups and companies and I was ready for rejection (this is important!).</p><p>Every day for 2 months I had phone calls with recruiters, technical screenings, and on-site interviews. It is very convenient that now everything is online. After almost a month of technical screenings, I even said that I liked the interview process, there are so many interesting problems and people, but then the onsite time came after the first 5-hour interview, and my opinion changed in a completely different direction, it’s so hard!</p><p>In the beginning, I had rejections and it was frustrating of course. But as soon as I received the first offer, my motivation immediately grows until the next rejection.</p><p>I was ready for rejection, but it’s still unpleasant to hear, especially when you spent 5–6 hours and they send you a standard reply that we decided to move with another candidate without any feedback. This motivated me to reflect and analyze what went wrong. I took notes and tried to find answers on how to solve the problem or what needed to be clarified and how to design something. This helped in future interviews to combine different solutions into one and produce a high-quality solution.</p><p>Also, communication with recruiters helped me improve my English, at the beginning I might not even understand half of what they were saying to me, but then I got used to it and it was much easier.</p><p>In the end, I had really good interviews, but I kept getting rejected for some of them. And the worst thing is, you don’t understand what went wrong.</p><h3>The interview process</h3><p>My interview stats:</p><p><strong>Tech Screens (26)</strong>: Meta, Amazon, Apple, Google, Microsoft, Lyft, Uber, LinkedIn, Roku, Salesforce, PayPal, DoorDash, Robinhood, Roblox, Intuit, Zoom, Grammarly, Imply, Disco, Square, SigmaComputing, LiveRamp, Zoox, Palo Alto Networks, Snowflake, Aurora</p><p><strong>Onsite interviews (15)</strong>: Meta, Amazon, Google, Microsoft, LinkedIn, Roku, Salesforce, PayPal, DoorDash, Zoom, Grammarly, SigmaComputing, LiveRamp, Zoox, Aurora</p><p><strong>Offers</strong>: Google, Roku, Microsoft, PayPal, SigmaComputing, LiveRamp</p><p>When applying for a Front End position, you will likely be asked only questions about the frontend, but at least 1 algo-problem of the easy-mid level will be asked, mainly about the data structure and its processing (there are not a lot in JS :)). But some like to ask algorithms the old-fashioned way.</p><p>All of the preparation materials I mentioned above covered the interview questions.</p><p>The process is pretty standard:</p><ol><li>Call with recruiter</li><li>Technical screening</li><li>Onsite (virtual) interview:</li></ol><ul><li>Algorithms</li><li>Tasks for coding a widget or a JS function</li><li>System design, with a focus on Front-End</li><li>Behavioral interview</li></ul><p>4. Negotiation</p><p><strong>1. Call with a recruiter</strong></p><p>On a call with a recruiter, you discuss general questions, and learn more about the company and the team you are interviewing. They ask about your work permit. In conversation, they ask about your experience and check your English. They find out what stage of your job search you are at and can build on this, for example, to speed up your interview process (In Aurora, I said that I completed all my interviews and if we can quickly go through all the stages, I agree. As a result, all the stages were done to me in 4 days, and onsite in just 3 rounds).</p><p>Calls often happen before you have sent your CV. Only if everything went well and there is a match, you will be asked to send your CV. They may ask about your salary expectations, but I answered truthfully that I have no idea how much I am worth on the market since I just arrived. This was enough for them to pass over the question. You can ask for all the information you need in the same call, including the technical stack of the team. If you have questions that are important to you, this is the time to ask them. For me, it was the terms for the green card and the tech stack.</p><p>Recruiters respect your time, so you coordinate each call according to the calendar, choosing from the recruiter’s one, or the recruiter can choose from your calendar.</p><p>Do not specify your salary expectations in any case, if they are very demanding (it has only happened once), specify a wide range. Turo’s recruiter repeatedly asked me what I expected, and when I gave him the range he said our compensation was 2 times less and we wouldn’t be able to match.</p><p><strong>2. Technical screening</strong></p><p>So you have passed the first stage and you have been assigned a technical screening. Usually, it is 45 minutes. On it, again, you will tell a little about yourself, you will be asked questions about your experience and will be given to solve some small problem (in 90% it will either make a small widget in JS and a framework, or an easy problem for algorithms, or rather data structures that is in JS). Occasionally, there were problems on Hackerrank with HTML, CSS, and JS, 2–3. These are fairly simple to solve. Sometimes you can use any editor of your choice. But most of the time I send a link to my online editor (even with code highlighting).</p><p>The most important thing is not to be silent, to think out loud so that the interviewer follows your thoughts.</p><p>Related to code execution, it’s 50/50, sometimes you need to run the code when you want and as much as you want, and sometimes I don’t even need to run the code (there’s not even such a possibility).</p><p>There was one time when I was asked to design an elevator system at a technical screening (without code), it didn’t end well :)</p><p><strong>3. Onsite(virtual) interview</strong></p><p>The most difficult stage of the interview, as it duration 3–6 hours. Many companies allow you to split it into 2 days, this is up to you.</p><p>It consists of coding, system design, and behavioral interview.</p><p>You can ask the recruiter about each round of onsite to understand what to expect from them.</p><p><strong>Coding rounds</strong> are similar to technical screening: find out the requirements, discuss the solution, code, and test it.</p><p><strong>System design</strong></p><p>Always focused on front-end issues, no need to talk about highly loaded systems, databases, etc. You just need to describe some functionality in the browser, ways to optimize, customize and expand, describe how to transfer data to the server, how to store it, where to store it, and why. Sometimes you need to design several endpoints with request and response structures. Don’t forget accessibility, it’s very important!</p><p><strong>Behavioral interview</strong></p><p>Here you can expect questions about your experience, projects, and teamwork. Basically, these questions are “Tell me a situation when you ..”</p><p>In general, the questions asked about the most challenging project, the conflict in the team, what we did when deadlines were approaching and we didn’t have time, and what our biggest failure was.</p><p>All stories should be told according to the STAR (situation — task — action — result) methodology. The story shouldn’t be very long. You will be asked clarifying questions if you didn’t explain something or the interviewer misunderstood you.</p><p>In most cases, the hiring managers conduct the interviews. In the end, this is a great opportunity for you to ask all your questions about the team and the product.</p><p><strong>Negotiation</strong></p><p>There is no less stressful or important stage. It took me almost a month. With some companies, there were even several rounds, on average, I raised offers for 70–100k. Ask for feedback about you to better understand how good you were and use it as a negotiation tool. But nothing works better than a counteroffer. But it is important not to go too far, look at the compensations on the levels.fyi website beforehand in order to understand the range.</p><h3>Some conclusions about companies</h3><p>In all companies recruiters do a very good job and support you every step of the way, tell you what to expect in each round, how to prepare, and tell you what the interview process looks like in general.</p><p><strong>Amazon</strong>: I had the worst interview ever. At all rounds I had problems understanding what the interviewer wanted from me, I clarified the requirements most of the time and explained my solution because for some reason they couldn’t understand it. And when they started asking questions about JavaScript during the coding process, it turned out that they didn’t know it and had to spend more time explaining why I use it and how it works. As a result, there were 5–7 minutes left for coding, but this was enough to finish. In the last round, I got the hard problem with trees, that I didn’t fully solve.</p><p><strong>Microsoft</strong>: Some of the interviewers again didn’t know JavaScript, only asked algorithmic problems and asked questions about how JavaScript works. It was more like an interview for a full-stack position.</p><p><strong>Zoox</strong>: Only math problems and algorithms were asked.</p><p><strong>Aurora</strong>: Again, only algorithms were asked, although the position is pure Front-End. However, my friend’s interview focused only on front-end questions.</p><p><strong>Meta</strong>: I didn’t expect so much attention from this company. I had a lot of calls with a recruiter, the duration of some was an hour, where he told everything in detail about the interview process, gave preparation materials, asked how the preparation was going and gave advice, including how to behave in an interview, what to ask, what better not to ask. The questions were on the front-end focus. After the onsite, the hiring freeze started right away.</p><p><strong>LinkedIn</strong>: They have an Ember.js framework, so questions are only about pure JavaScript and the front end.</p><p><strong>Apple</strong>: Lost my feedback after the technical screening. Still searching.</p><p><strong>Google</strong>: The interview process was with a front-end focus. After getting approval from the Google Hairing Committee, your next step is team matching. I had mixed feedback between L5 and L4 levels. As a result, the committee gave me L4 without additional interview stages. Only after a successful team match, they will send you an offer with numbers, but how long this process can take depends on many factors.</p><p>I had 2 team calls a week, although I could do them every day. The process took 2 weeks.</p><p>The criteria by which I compared the teams:</p><ul><li>Team size. Frontend, backend, infrastructure engineers.</li><li>Tech stack (all Angular).</li><li>Promotion to L5 (time and opportunity).</li><li>Product.</li><li>Responsibilities.</li><li>Front end or full stack position. There was even a backend only.</li><li>Development process.</li><li>Who are the users of the product, and how many? Perhaps this is an internal project or a large one for a large number of users.</li><li>Evaluated how comfortable communicating with the manager or team leader is for me.</li></ul><p>As a result, I matched with the Google Analytics team, which is responsible for the performance of this product. In this team, I saw many opportunities for growth and metrics for promotion.</p><h3>How do I accept the offer?</h3><p>I compared offers and decided which one to accept according to the following criteria.</p><p><strong>1. Product.</strong></p><p>It is very important that the product is of interest to you. I have many years of experience in developing streaming platforms and know the needs of users and developers. I can learn a lot and see many challenges for myself in such products. Roku gives me this opportunity.</p><p><strong>2. Tech stack and tools.</strong></p><p>I don’t like Angular, I prefer React.js. This was one of the most important reasons why I chose Roku.</p><p><strong>3. Work-life balance.</strong></p><p>This is a very important thing. I don’t want to burn out. During the interview process, you can ask questions about it and listen carefully to the answers.</p><p><strong>4. Opportunities for growth.</strong></p><p>Growth in technical terms and within the company to the lead position (Staff)</p><p><strong>5. Position level.</strong></p><p>After the position of engineering manager, I was not ready for middle positions (yes, there were those too).</p><p><strong>6. Total compensation.</strong></p><p>Base and stock. Roku pays 85% in cash for senior positions, which is more profitable for me, as a beginner in this country, since at this stage money is needed here and now.</p><p><strong>7. Green Card Process.</strong></p><p>Some companies start the green card process from the 1st working day, some after 3, 6, and 12 months. I filtered companies based on 1 day and 3 months. But as it turned out, these terms can also be negotiated, I was able to negotiate from 3 months to 1 working day.</p><p>An important nuance, Meta does not issue green cards, I asked them about it at every call, and at every stage of the interview, but I never received an answer, any one at all. But according to information on the Internet, everything is bad with them.</p><p><strong>8. Team size and responsibilities.</strong></p><p>I don’t like working in a team where you are one Front End engineer, or even 2. I want to grow and learn. The level of engineers in the team was also important for me.</p><p><strong>9. Remote work or office work.</strong></p><p>I prefer office work. Working from home is not comfortable for me. Some companies now offer to work 3 days in the office, 2 days remotely, and some offer full remote work.</p><p><strong>10. Office location.</strong></p><p>I live in San Jose and some companies have offices in San Francisco. It will take you at least 1.5 hours to drive here. Do you want to spend 3 hours a day on this?</p><h3>Tips</h3><ul><li>Do not schedule more than 3 (but preferably 2) on-site per week. Last week I had 4 on-site in a week and it was hell! But I got 2 offers :)</li><li>In an interview, your skills grow exponentially, so do not immediately pass the interview with the company of your dreams.</li><li>After the interview you can talk to someone, it helps to relax.</li><li>Do work on the mistakes after each interview to understand what could have gone wrong, look for answers to questions and tasks that were in the interview and try to figure them out.</li><li>Prepare the text for your self-presentation for 1–1.5 minutes, you will tell it at each stage of the interview.</li><li>For a behavioral interview, prepare and practice as many STAR stories as you can, I had about 20 that covered almost all questions. It took about a month to prepare them.</li><li>Buy a paid subscription to Calendly (or a similar service) to make it easier to manage your interviews. Sending the dates in an email means they can respond within a week, and demand 5 dates (respectively), so these 5 days are blocked for you and you cannot schedule other interviews on them.</li></ul><p>If you have any questions or topics that I have not covered, ask in the comments here or on my <a href="https://t.me/front_end_interview">Telegram channel</a>!</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30e2cea7b99e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-i-relocated-to-the-usa-looked-for-opportunities-offers-i-received-from-maang-and-more-30e2cea7b99e">How I Relocated to the USA, Looked for Opportunities, Offers I Received from MAANG, and More</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Star Rating Widget With React.js and Optimize It]]></title>
            <link>https://medium.com/better-programming/how-to-implement-star-rating-widget-with-react-js-and-optimize-it-e3625f3104f?source=rss-d4d014fc538c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3625f3104f</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yan Tsishko]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 12:50:32 GMT</pubDate>
            <atom:updated>2022-07-26T00:32:16.047Z</atom:updated>
            <content:encoded><![CDATA[<h4>Designing it from start to finish</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*aQISnNuoThfg6azDeB6ZBw.png" /><figcaption>Image by author</figcaption></figure><p>In this article, I want to cover the problem you can have in an interview for the frontend position — implementing the star rating widget.</p><p>I had 15 onsite interviews in the last five months and had offers from Google, Roku, Microsoft, and others.</p><p>You should clarify requirements and implement that widget for ~45–50 min.</p><h3>Requirements</h3><p>Let’s start with the requirements of our widget.</p><ul><li>Displaying stars with dynamic count</li><li>Users can choose a rating</li><li>Allow read-only mode for displaying ratings of other users without editing</li><li>Change the label for the widget</li><li>Change colors of start for empty and filled states</li><li>Extend set and hover events</li><li>Set size of stars</li></ul><h4>Mockup</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDvo2thuqM-GL1wBSTJdoA.jpeg" /><figcaption>Star rating mockup</figcaption></figure><h4>Component architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vu-HeEhXVWKTfJ3MFnMGmw.jpeg" /><figcaption>Component architecture of star widget</figcaption></figure><h4>Components implementation</h4><p>Let’s start with the props of our start rating component. With that props, we can configure our slider.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59361a9777bf015e114a44fb7c244a03/href">https://medium.com/media/59361a9777bf015e114a44fb7c244a03/href</a></iframe><p>In the Star Rating component, we need to implement the following:</p><ul><li>Extend set and hover functions for customer needs</li><li>Provide all configuration of the widget in Context</li><li>Render Label and StarsList</li></ul><p>We will save the current rating and hover values in the component’s local state. To avoid the count of props and drilling, I suggest using Context to provide configuration and current widget state.</p><p>setRatingFn and setHoverFn extends events with custom functions and provide current values. In read-only mode, these methods are disabled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/beda9c0923e9c6889c94d5fbd2814b88/href">https://medium.com/media/beda9c0923e9c6889c94d5fbd2814b88/href</a></iframe><p>For the label, we have a default function with custom text. If a user wants to use the custom text, we allow them to do that and use that method in the StarRatingLabel component in the render.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcddb3bd9872af8212d5a44dd776b664/href">https://medium.com/media/dcddb3bd9872af8212d5a44dd776b664/href</a></iframe><p>StarsList component render count of Star components from the configuration. The default value is five.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1085588fd545d8672a252991ecb11ed/href">https://medium.com/media/a1085588fd545d8672a252991ecb11ed/href</a></iframe><p>Each Star component knows its own value, and we can use that value for a set rating or display changes on hover. Using SVG allows controlling colors, size, and shapes of icons. If you want to provide the possibility to use other icons, users can set custom SVG in configuration. Also, SVG allows changing size without losing the quality of the image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3d6236aad999478d8a97921b0af50da/href">https://medium.com/media/a3d6236aad999478d8a97921b0af50da/href</a></iframe><p>Another approach can be using custom fonts, in the case you provide different icons for widgets.</p><h4>Optimization</h4><p>As you can see in the Star component, each time crating inline function, we can avoid that.</p><p>Let&#39;s change our Star component code. Need to add data attribute with value for the star and call onClick, onMouseEnter, and onMouseLeave methods without inline functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/808b891766f9eb6b68ef4f8a5ff873cc/href">https://medium.com/media/808b891766f9eb6b68ef4f8a5ff873cc/href</a></iframe><p>In the Star Rating component changed two methods: setRatingFn and setHoverFn. Here we can get value from the data attribute and use it.</p><p>With the OnmouseLeave event, we need to set the hover state to null. We can handle that by typing or creating a separate method and calling it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8971d5e8f34fe0fb37fbdbeb34fb743e/href">https://medium.com/media/8971d5e8f34fe0fb37fbdbeb34fb743e/href</a></iframe><p>One more approach can be using radio buttons and getting values from them.</p><h3>Conclusion</h3><p>Now you know how to create a custom star rating widget and what the requirements you can clarify with the interviewer.</p><p>All code you can see on <a href="https://github.com/yantsishko/star-widget-from-scratch-reactjs">GitHub</a>.</p><p>Other articles you can read:</p><ul><li><a href="https://betterprogramming.pub/implementing-image-and-text-slider-with-react-js-and-optimizations-7a16af998548">Implementing Image and Text Slider With React.js And Optimizations</a></li></ul><pre><strong>Want to Read More About Front-End Interviews??</strong></pre><pre>Here&#39;s <a href="https://t.me/front_end_interview">my blog</a></pre><p>Good luck with your interviews!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3625f3104f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-implement-star-rating-widget-with-react-js-and-optimize-it-e3625f3104f">How to Implement Star Rating Widget With React.js and Optimize It</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Image and Text Slider With React.js And Optimizations]]></title>
            <link>https://medium.com/better-programming/implementing-image-and-text-slider-with-react-js-and-optimizations-7a16af998548?source=rss-d4d014fc538c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a16af998548</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yan Tsishko]]></dc:creator>
            <pubDate>Thu, 14 Jul 2022 01:27:10 GMT</pubDate>
            <atom:updated>2022-07-26T00:31:55.353Z</atom:updated>
            <content:encoded><![CDATA[<h4>Designing it from start to finish</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*095nJUPNO-S22umjtH5Hwg.png" /></figure><p>In this article, I want to cover the problem you can have in an interview for the Frontend position — implementing Image Slider.</p><p>I had 15 onsite interviews last 5 months and had offers from Google, Roku, Microsoft, and others.</p><p>You should implement that widget for ~45–50min and tell about optimizations. This information I will try to cover here. The main goal is not to implement Image Slider with a lot of functionality, the goal is to explain how to implement and optimize.</p><h3>Requirements</h3><p>Let&#39;s start with the requirements of our widget.</p><ul><li>Displaying images with cats from API with some size limit</li><li>Displaying the description or title for each image</li><li>Possibility to navigate between images with arrows</li><li>Possibility to change slide by touch on mobile devices</li><li>Possibility to jump to any slide</li><li>AutoPlay for slider</li><li>Possibility to customize width and height for slider</li><li>The slider should be responsive</li><li>Slider images should be downloaded efficiently and displayed as fast as possible</li></ul><h4>Mockup</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uV-bwdGEXbKpKpmacQhpA.jpeg" /><figcaption>Slider mockup</figcaption></figure><h4><strong>Rendering in browser</strong></h4><p>For the first and simple implementation, we render all slides in the browser and display only parts in the viewport or in the slider element (when we set width or height). These solutions download all images for all slides and have N DOM elements, where N — number of slides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rged1XIRcIKE5Yk4qkHw9Q.jpeg" /><figcaption>Rendering in browser</figcaption></figure><h4>Component Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3eETQb29SPIJ4JoJhHR-g.jpeg" /><figcaption>Component Architecture of Slider</figcaption></figure><h4>Components Implementation</h4><p>Let’s start with the props of our Slider Component. With that props we can configure our slider.</p><pre>{</pre><pre>   autoPlay: boolean,</pre><pre>   autoPlayTime: number,</pre><pre>   width: &#39;%&#39; | &#39;px&#39;,</pre><pre>   height:  &#39;%&#39; | &#39;px&#39;,</pre><pre>}</pre><p>In the Slider component we need to implement the following:</p><ul><li>load images</li><li>implement a method for navigation by arrows</li><li>implement a method for navigation by dots</li><li>implement touch navigation</li><li>autoplay functionality</li><li>rendering slides, arrows, and dots</li></ul><p>We will save the current slide number and downloaded images in the component’s local state. To avoid count of props and drilling suggest using Context to provide changing slides methods and current slider information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c3c3f18147129b3fff1d05af418cbe0/href">https://medium.com/media/3c3c3f18147129b3fff1d05af418cbe0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c2572d31a1e11f10c42ceb0fb904d47/href">https://medium.com/media/1c2572d31a1e11f10c42ceb0fb904d47/href</a></iframe><p>As you can see on Component architecture Slider components contain 3 components: SlideList, Arrows, and Dots.</p><p>We have 2 arrows on the left and on the right sides.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f918e01d4cd969dd6c31df20f3ad69/href">https://medium.com/media/52f918e01d4cd969dd6c31df20f3ad69/href</a></iframe><p>For displaying arrows on both sides we can style it by CSS</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cf89ca7a2750b76efe52809518b559d/href">https://medium.com/media/3cf89ca7a2750b76efe52809518b559d/href</a></iframe><p>We know the count of slides and can render the correct number of dots.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd146f5a8384905d651032f50930484c/href">https://medium.com/media/dd146f5a8384905d651032f50930484c/href</a></iframe><p>Each dot looks to follow</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b3c4af5db02a410e96bee5c745ab74e/href">https://medium.com/media/3b3c4af5db02a410e96bee5c745ab74e/href</a></iframe><p>For displaying slides in SlideList we can get items from context and render the Slide component with keys and data about the slide.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1194112b94b0b5b33b667a324dfde320/href">https://medium.com/media/1194112b94b0b5b33b667a324dfde320/href</a></iframe><p>To achieve such animation need to use transform and translateX in styles. We move our content to the next slide by slide number in our array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*8h1jP1yaIMl_Y3drI6OieA.gif" /><figcaption>Animation with translateX</figcaption></figure><p>Slide component contains 2 components: SlideImage and SlideTitle. This architecture allows for the addition of new functionality for the future for each slide.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e68cbfa93ce1dc35f4c660d60aac6e97/href">https://medium.com/media/e68cbfa93ce1dc35f4c660d60aac6e97/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28165965046b414061c5e769dc6f7a7c/href">https://medium.com/media/28165965046b414061c5e769dc6f7a7c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86e2f6bd02cbc60bc33350695acde465/href">https://medium.com/media/86e2f6bd02cbc60bc33350695acde465/href</a></iframe><h4>How to optimize the solution?</h4><p>Imagine that you have a lot of images in the slider and you need to optimize it. Optimization depends on the change slides animation ... yes, animation.</p><p>I see here 2 ways to optimize.</p><ol><li>Displaying 3 slides at one-time</li><li>Displaying only one slide at a time</li></ol><p>Let&#39;s see them.</p><h4>3 slides at one-time optimization</h4><p>If you want to use transform for changing slides you can use the following optimization.</p><p>Here we display only 3 slides at one time. Our active slide in the middle, and prev and next slides, because the user more frequently can click to prev or next arrows, or in case of autoplay we move forward each time.</p><p>When we move to prev or next slide we calculate the new 3 slides and render them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Vqor2pQWcf1Nk1oLnAZVA.jpeg" /><figcaption>Rendering 3 slides at one-time</figcaption></figure><h4>One slide optimization</h4><p>If you want to use animation in CSS you can use one slide and each time display one slide with information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ipCH3MVNKDgS66kBNbehA.jpeg" /><figcaption>Rendering one slide at one-time</figcaption></figure><p>Example of animation effects that can be applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*TgQoqITNbAs1VIx6xD_aiw.gif" /><figcaption>Animation with opacity</figcaption></figure><p>For that optimization need to add some changes to our solution.</p><p>There is no need to use now SlidesList component, we should render only one Slide component (line 99).</p><p>Also, we should control the animation effect and apply it only when changing slide content (line 41).</p><p>And the last change, for better user experience we should preload images previous and next ones from the current slide (line 25).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80b29241480d2388c8732cb2768daf9f/href">https://medium.com/media/80b29241480d2388c8732cb2768daf9f/href</a></iframe><p>In Slide we need only one change. It’s applying class with animation when slide changing is triggered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47128ce74f37bbd947ec1c4fce6c6645/href">https://medium.com/media/47128ce74f37bbd947ec1c4fce6c6645/href</a></iframe><p>Implementation of fadeIn animation in styles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e602c2bebfe5216c184cee278badc49/href">https://medium.com/media/0e602c2bebfe5216c184cee278badc49/href</a></iframe><h4>Another optimization points</h4><ol><li><strong>Correct image size</strong>— There is no need to use full HD resolution if you slider with limited size.</li><li><strong>Use WebP format for images</strong> —<strong> </strong>It allows for reducing the size of images. It compresses at least 20–30% better than jpg and png.</li><li><strong>Don&#39;t use 100% quality images</strong>— There is no need to use 100% quality images. From my experience, 70— 85% of quality looks the same as 100%, but the size of the image is less.</li><li><strong>Minify JavaScript and Styles.</strong></li><li><strong>Use CDN to store images.</strong></li><li><strong>Use Brotli for compression.</strong></li></ol><p>The final size of data is less than gzip for 14–21%</p><h3>Conclusion</h3><p>There is no special knowledge to implement your own Image Slider. You need to practice doing that without Googling and in limited time.</p><p>All code you can see on <a href="https://github.com/yantsishko/slider-from-scratch-reactjs/tree/main">GitHub</a>.</p><p>In the next articles, I will cover the Tree View widget, Star widget, Google doc, and Google sheet system design.</p><p>Other articles you can read:</p><ul><li><a href="https://betterprogramming.pub/how-to-implement-star-rating-widget-with-react-js-and-optimize-it-e3625f3104f">How to Implement Star Rating Widget With React.js and Optimize It</a></li></ul><pre><strong>Want to Read More About Front-End Interviews?<br></strong><a href="https://t.me/front_end_interview">My blog</a></pre><p>Good luck with your interviews!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a16af998548" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/implementing-image-and-text-slider-with-react-js-and-optimizations-7a16af998548">Implementing Image and Text Slider With React.js And Optimizations</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use DB8 on LG WebOS instead of LocalStorage and indexedDB]]></title>
            <link>https://itnext.io/how-to-use-db8-on-lg-webos-instead-of-localstorage-and-indexeddb-bfee6979094b?source=rss-d4d014fc538c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfee6979094b</guid>
            <category><![CDATA[webos]]></category>
            <category><![CDATA[lg]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[smart-tv]]></category>
            <dc:creator><![CDATA[Yan Tsishko]]></dc:creator>
            <pubDate>Thu, 12 May 2022 22:03:52 GMT</pubDate>
            <atom:updated>2022-05-12T22:03:52.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zH3C8P1n3QwppHtqXHr5g.jpeg" /><figcaption>Photo by<a href="https://unsplash.com/@jenskreuter?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Jens Kreuter</a> on<a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Unsplash</a></figcaption></figure><h3>What is DB8?</h3><p>“DB8 is a storage method of webOS TV. DB8 is designed to meet the needs of robust, high-performance apps. DB8 is a service available on Luna Bus, and interfaces to an embedded JSON database. “ — <a href="https://webostv.developer.lge.com/develop/app-developer-guide/db8/webos-db8-basics/">https://webostv.developer.lge.com/develop/app-developer-guide/db8/webos-db8-basics/</a></p><p>Main DB8 features include:</p><p>- Enabling high-speed access and queries.</p><p>- Storing JSON objects.</p><p>- App-aware access control.</p><p>- Paging support for queries that can retrieve up to 500 objects at a time.</p><p>- Support for change notification.</p><p>- Data object validation through schema enforcement.</p><h3>Why we should use DB8 instead LocalStorage?</h3><p>The apps on SmartTVs (Tizen, WebOS) can work with LocalStorage because it’s a browser (Chromium) without any issues. But here is one nuance. When you remove the app from TV and then install it again on WebOS 6.0 localStorage stays the same as the previous state (before removing the app). You can’t handle this behavior and clear it manually.</p><p>Real-life example: if you logged in to your account in-app and want to sell the TV, you remove the app from this TV and a new customer installs this app again, and what does he see? Yes, he sees your logged-in account, unfortunately.</p><p>On Tizen when you remove the app it clears the localStorage information too.</p><p>DB8 allows to update the app with saving data, but after removal, it clears all app information.</p><p>Also, DB8 can be used as NoSQL DB</p><h3>Comparing DB8, LocalStorage, and indexedDB</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iU3tPjR-I3W2pa9dVwsYwA.png" /></figure><p>As you can see DB8 is most similar to indexedDB, and we solve the most important thing with clear data only.</p><h3>Implementing getItem in DB8</h3><p>For getting items I used the <strong>find</strong> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6340c3153bdce2b5d2ae29badb9f29b/href">https://medium.com/media/b6340c3153bdce2b5d2ae29badb9f29b/href</a></iframe><h3>Implementing setItem in DB8</h3><p>In DB8 we can’t update data directly. That&#39;s why I removed the prev value and create a new Kind using <strong>putKind</strong> and save a new value using the <strong>put</strong> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b79d0e436c351d3acfe137869585a40f/href">https://medium.com/media/b79d0e436c351d3acfe137869585a40f/href</a></iframe><h3>Implementing removeItem in DB8</h3><p>For removing data we should use the method <strong>delKind.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07276e4e1621c2acf78c283c4e0e64e8/href">https://medium.com/media/07276e4e1621c2acf78c283c4e0e64e8/href</a></iframe><h3>Clear storage</h3><p>You can’t clear all storage, you can remove records by ids only. But you can’t get the list of ids too. Records in-app connected with the owner, and after app removal, it clears all automatically.</p><h3>Conclusion</h3><p>I don’t know why LG decided to complex life of developers for WebOS 6, but we should use DB8 :)</p><p>In general, we can use indexedDB which allows us to do similar things but we can’t clear data after the app deleting.</p><p>According to performance, it works pretty fast, but for user expectations, it works with the same speed as indexedDB and localStorage.</p><p>More examples you can find in <a href="https://webostv.developer.lge.com/develop/code-samples/db8/">docs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfee6979094b" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-use-db8-on-lg-webos-instead-of-localstorage-and-indexeddb-bfee6979094b">How to use DB8 on LG WebOS instead of LocalStorage and indexedDB</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[How to check network connection on SmartTV (WebOS and Tizen)]]></title>
            <link>https://itnext.io/how-to-check-network-connection-on-smarttv-webos-and-tizen-75256c67584b?source=rss-d4d014fc538c------2</link>
            <guid isPermaLink="false">https://medium.com/p/75256c67584b</guid>
            <category><![CDATA[webos]]></category>
            <dc:creator><![CDATA[Yan Tsishko]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 08:09:01 GMT</pubDate>
            <atom:updated>2022-01-04T08:15:22.516Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oscYvlfmyKNQvX2gIbBEXQ.jpeg" /><figcaption>Photo by<a href="https://unsplash.com/@jenskreuter?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Jens Kreuter</a> on<a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Unsplash</a></figcaption></figure><p>Today I want to tell you about how to implement the No Connection feature on SmartTV for webOS and Tizen platforms. It’s sound pretty easy and you can ask me, what you can tell us new, but believe me, I can :)</p><p>This article is about how to detect the network connection.</p><p>At the current moment I know 3 ways how to check the network connection and each of them has pros and cons, lets go through each.</p><h4>1) Checking network status in the browser</h4><p>The browser has listeners for subscription to network state change. And I started from this implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d00c45c8cd4a82235b9d1fbeeadef8ef/href">https://medium.com/media/d00c45c8cd4a82235b9d1fbeeadef8ef/href</a></iframe><p>It works perfectly when you test this feature in the PC/laptop browser but some time later I was notified, that it doesn’t work. Why?</p><p>On TVs, this implementation works only when you unplug the cable from the TV, but in real-life we have network connection errors in another case. The test case was unplugging the LAN cable from the router and the browser absolutely doesn’t detect this case, it says that the browser is onLine.</p><p>Move to the next implementation where we can detect this case.</p><h4>2) Checking network status with native SmartTV SDK</h4><p>WebOS and Tizen support checking network connections using native SDK.</p><p>For WebOS, you can use <a href="https://webostv.developer.lge.com/api/webos-service-api/connection-manager/"><strong>Connection Manager</strong></a><strong> </strong>and use one-time check or subscribe to changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4070b8b1c65e299c4b63ff8999c94cf4/href">https://medium.com/media/4070b8b1c65e299c4b63ff8999c94cf4/href</a></iframe><p>For Tizen you can use <a href="https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/network-api.html"><strong>Network API</strong></a> and also you can use one-time check or subscribe to changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86238f6cd980f294117a6b9ed6b0a205/href">https://medium.com/media/86238f6cd980f294117a6b9ed6b0a205/href</a></iframe><p>The expected result of using SDK is that smartTV should understand when a network connection exists or not.</p><p>The reality looks another.</p><h4><strong>Tizen:</strong></h4><p>When you unplug the LAN cable from the TV it triggers network state change immediately, as a browser check.</p><p>When you unplug the LAN cable from the router nothing happens during 30–40 sec, only after that time Tizen detects that there is no network. It’s more than nothing and we can work with this.</p><h4><strong>WebOS:</strong></h4><p>Unplug LAN cable from TV triggers network state change immediately.</p><p>Unplug LAN cable from the router doesn’t trigger network state change after 30sec, 1min, and after 1 hour. It was a surprise for me.</p><p>At that moment, I started to think about how to implement this feature for all platforms and with a little delay.</p><h4>3) Checking network status by periodically polling a BE or third-party endpoint</h4><p>I saw only one solution how to reach the goal and it’s periodically polling. For this ping, we can use some health check endpoint on the backend side or third-party endpoint (Google for example).</p><p>If we have a response status between [200, 300) we can say that we have a connection.</p><p>If we have some error we can say that something is wrong and there is no network.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdb24788d81c1222a9ab93ecbfe64b54/href">https://medium.com/media/cdb24788d81c1222a9ab93ecbfe64b54/href</a></iframe><p>This implementation works correctly on WebOS and Tizen in all cases with a delay of 2 sec.</p><p>You can add a timer for detection if something wrong and abort the request manually after some time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecba7e7398cd0820a72cfa9629946443/href">https://medium.com/media/ecba7e7398cd0820a72cfa9629946443/href</a></iframe><p>You can’t use <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController">AbortController</a> and fetch here, because Chromium on Tizen 4 doesn’t know such interface, that&#39;s why I used XMLHttpRequest.</p><p>In this case, I had false-positive results after 10–40 min when requests sending without any response during 500ms, TV processes request with lower speed than PC and you should to understand it.</p><p>Also you can have a false-positive result when the server is not available at the current moment or has a high load and you show a No connection screen, but after retry it is available. It’s not user-friendly. A possible solution to this issue can be the implementation of a solution box where you can check the majority of positive results but it increases the delay time between loss connection and showing screen.</p><h4>Conclusion</h4><p>Not always simple features can be so easy, especially when you working with SmartTV. Using two approaches, SDK and periodically polling can cover all cases and you will have low latency between loss connection and it detection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75256c67584b" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-check-network-connection-on-smarttv-webos-and-tizen-75256c67584b">How to check network connection on SmartTV (WebOS and Tizen)</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[Solving JavaScript Problems from Bigfrontend (BFE): Throttle and Debounce]]></title>
            <link>https://itnext.io/solving-javascript-problems-from-bigfrontend-bfe-throttle-and-debounce-87a809e5952b?source=rss-d4d014fc538c------2</link>
            <guid isPermaLink="false">https://medium.com/p/87a809e5952b</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[vanilla-javascript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[faang-interview]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Yan Tsishko]]></dc:creator>
            <pubDate>Thu, 21 Oct 2021 10:21:18 GMT</pubDate>
            <atom:updated>2021-10-21T10:21:18.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6kVZW_FetYPUv9jMmPYAQ.png" /></figure><p>In this series of articles, I want to solve BFE problems (<a href="https://bigfrontend.dev/">https://bigfrontend.dev</a>) and analyze solutions. BFE is a site with tasks that allow you to prepare for a front-end interview and expand your knowledge of JavaScript.</p><p>Today I want to consider 2 problems, they are <a href="https://bigfrontend.dev/problem/implement-basic-throttle">throttle</a> and <a href="https://bigfrontend.dev/problem/implement-basic-debounce">debounce</a>.</p><h3>1. Throttle</h3><p>Theory:</p><p>Throttle allows you to execute the function only once in a given time interval.</p><p>In practice:</p><p>For example, we need to handle the scrolling of the page and execute some <strong>fn</strong> function that works with the coordinates of the scroll. We can subscribe directly to the <strong>onscroll</strong> event, but it will be called very often (depending on how fast we scroll), but even if we do it quickly, events will be more than 1–2. You can decorate the executed function in throttle and execute it once every N ms.</p><p>It will work like this:</p><p>1. The first time onscroll is called, the decorated variant passes the call to <strong>fn</strong> immediately. The user sees the changes.</p><p>2. If we keep scrolling the page, then nothing happens N ms. Onscroll events are ignored.</p><p>3. When the scroll stops, the decorated function will wait until N ms has passed and execute <strong>fn</strong> with the last coordinates. It will process the final coordinates where the scroll stopped.</p><p>Solution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50a2ee3365153a9f17e376f5b1fe9913/href">https://medium.com/media/50a2ee3365153a9f17e376f5b1fe9913/href</a></iframe><p>Let’s analyze the solution:</p><p>The throttle function takes 2 arguments: the function to be executed and the timeout in ms.</p><p>In lines 7–9, we need to save our timer, which we create for the trigger of function calls at a given interval, and we need to save the calling context and arguments so that when the timer runs out, we can execute the function with the correct context and parameters.</p><p>Line 11 returns the function because we need to make a closure and decorate the original function in the throttle.</p><p><em>​​const throttled = throttle(func, 3)</em></p><p>Now we should process 2 options: the first call and subsequent ones. The first call should work immediately, without waiting for the timer to expire. Subsequent ones should be “overwritten” and the most recent ones should be called when the timer expires.</p><p>Checking is the first call or not is performed according to the running timer, so in line 12 you can see it, if this is not the first call, we just save the context and arguments.</p><p>If this is the first call, then the function is immediately executed (line 16) and the timer (line 18) is started with the specified time interval. An additional check for arguments inside the timer is so that if we had only one call (we did the first one right away) so that it would not be called again after the time expired. If there were calls then after the time has passed the function will be called with the saved context and arguments (line 20), the timer is cleared (line 22), the data of the last call is also cleared (lines 23, 24).</p><h3>2. Debounce</h3><p>Theory:</p><p>The function will be executed only after the specified time once the user stops the event call.</p><p>In practice:</p><p>We need to handle the scrolling of the page and execute the <strong>fn</strong> function that works with the coordinates of the scroll. Debounce will call the <strong>fn</strong> after N ms, if no more event is triggered after the timer starts. If a new event were triggered and the timer is not ended then the previous timer canceled and a new one started.</p><p>It will work like this:</p><p>1. When onscroll is called for the first time, the decorated function starts a timer with a call to <strong>fn</strong>.</p><p>2. If we continue to scroll the page, then the previous timer is canceled and a new one starts.</p><p>3. If no onscroll events occur at the specified time N ms then the <strong>fn</strong> function is executed with the context and arguments of the last event.</p><p>Solution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e019cbf40ff3135a926090c1cb6a90e/href">https://medium.com/media/8e019cbf40ff3135a926090c1cb6a90e/href</a></iframe><p>The debounce function takes 2 arguments: the function to be executed and the timeout.</p><p>On lines 8–10, we need to save our timer, which we create for the trigger of function calls when the time expires, and we need to save the calling context and arguments so that when the timer runs out, we can execute the function with the correct context and parameters.</p><p>Line 12 returns the function because we need to make a closure and decorate the original function in debounce.</p><p>​​const debounce = debounce(func, 3)</p><p>The function that will run when the time expires is line 16. We call the original <strong>fn</strong> function with the saved context and arguments of the last call and set them to null.</p><p>With each subsequent call, we should cancel the timer and restart it, in line 23 cancellation is implemented.</p><p>Line 25 starts the timer by calling our <strong>fnCall</strong> function after the specified wait time.</p><h3>Conclusion</h3><p>As you can see, there is nothing difficult in the implementation of these methods. I hope the described algorithm from life is better to remember how the throttle and debounce works and what the difference is.</p><p>In the next article, we will analyze these problems with follow up (solving <a href="https://bigfrontend.dev/problem/implement-throttle-with-leading-and-trailing-option">throttle</a> / <a href="https://bigfrontend.dev/problem/implement-debounce-with-leading-and-trailing-option">debounce</a> with leading and trailing options)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87a809e5952b" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/solving-javascript-problems-from-bigfrontend-bfe-throttle-and-debounce-87a809e5952b">Solving JavaScript Problems from Bigfrontend (BFE): Throttle and Debounce</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[How To Blur Objects in Real-Time With Video and Canvas]]></title>
            <link>https://itnext.io/how-to-blur-objects-in-real-time-with-video-and-canvas-898cddc01ae6?source=rss-d4d014fc538c------2</link>
            <guid isPermaLink="false">https://medium.com/p/898cddc01ae6</guid>
            <category><![CDATA[confidentiality]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[javascript-video]]></category>
            <dc:creator><![CDATA[Yan Tsishko]]></dc:creator>
            <pubDate>Tue, 31 Aug 2021 09:49:30 GMT</pubDate>
            <atom:updated>2021-08-31T09:49:30.129Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gR0d_5b9uAJZrGYiAIYYqQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sigmund</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Confidentiality is a very important part of the modern world. When you shoot a video on your phone in a public place, people who get into the frame will not always be happy with it. To prevent this, faces are blurred or pixelated.</p><p>Today I want to share the implementation of such blur/pixelation of video (image) on the web.</p><p>What we have:</p><ul><li>browser</li><li>video</li><li>metadata of the video</li><li>array with faces coordinates for each frame (it was got before, using face detection algorithm)</li><li>knowledge about JavaScript, Canvas, and a bit of CSS</li></ul><p>We will blur the faces separately and the whole image, except for the faces.</p><p>It looks like this:</p><figure><img alt="How looks image with outer blur" src="https://cdn-images-1.medium.com/max/512/1*V-wYRWPhsTaSnA2ACqGIhQ.png" /><figcaption>Blur outside</figcaption></figure><figure><img alt="How looks image with inner blur" src="https://cdn-images-1.medium.com/max/512/1*2Z-ej_burVxomZ0aPi1Q3g.png" /><figcaption>Blur inside</figcaption></figure><p>Let’s go.</p><h3>How to Get Video’s Metadata</h3><p>First of all, we need to get the metadata of our video. To do this visit the site <a href="https://gpac.github.io/mp4box.js/test/filereader.html">https://gpac.github.io/mp4box.js/test/filereader.html</a> and upload the video.</p><p>Open src/constants/video.ts and change params.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc6e06aefae7849d1b384845191f72f0/href">https://medium.com/media/dc6e06aefae7849d1b384845191f72f0/href</a></iframe><p>framesCount it’s sample_counts in Box View -&gt; Tree View-&gt; moov -&gt; trak -&gt;mdia -&gt; minf -&gt; stbl -&gt; stts</p><figure><img alt="How to find framesCount param" src="https://cdn-images-1.medium.com/max/512/1*R-o8xcYD-S3YnlVjno-UfQ.png" /><figcaption>How to find framesCount param</figcaption></figure><p>framesDurations it’s sample_deltas in Box View -&gt; Tree View-&gt; moov -&gt; trak -&gt;mdia -&gt; minf -&gt; stbl -&gt; stts</p><figure><img alt="How to find framesDurations param" src="https://cdn-images-1.medium.com/max/512/1*RtqWh6eznDcr_DBbNTL1mQ.png" /><figcaption>How to find framesDurations param</figcaption></figure><p>timeScale it’s timescale in Box View -&gt; Tree View-&gt; moov -&gt; trak -&gt;mdia -&gt; mdhd</p><figure><img alt="How to find timeScale param" src="https://cdn-images-1.medium.com/max/512/1*3rHecoR2jfspQDOJYDiAAQ.png" /><figcaption>How to find timeScale param</figcaption></figure><p>We will need all this metadata to correctly determine the frame by video current time.</p><h3>How to Work With Video</h3><p>We have the video and we want to play it and blur faces on it. But we cannot just use a video tag, because we cannot edit it on the fly and we cannot do something with it in the browser. To do this you can draw this video on a canvas.</p><p>The rendering algorithm is pretty simple:</p><ol><li>Create a video element and set the URL to the video</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c2799ee35c2bfb774ff67dcca840870/href">https://medium.com/media/3c2799ee35c2bfb774ff67dcca840870/href</a></iframe><p>2. Create a canvas element and set its width and height as a video element, get its context</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28aee2749b6490628909731ffce360b8/href">https://medium.com/media/28aee2749b6490628909731ffce360b8/href</a></iframe><p>3. Draw a current frame on canvas</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be4122cfb3af32eee34975df184f4763/href">https://medium.com/media/be4122cfb3af32eee34975df184f4763/href</a></iframe><blockquote>* Method drawImage accepts interfaces: HTMLOrSVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas, that’s why we can pass the video element and the current frame will draw itself.</blockquote><p>After executing this code, we will see a black rectangle. This is because our video is currently in timeline 0. To see the image while opening the video, you need to do a little hack. When you render a video for the first time, set the current video time to 0.0001.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60c8ddba5341647425f2543e9e34deed/href">https://medium.com/media/60c8ddba5341647425f2543e9e34deed/href</a></iframe><p>Now another problem appears: we need to draw video frames during playback.</p><p>You can try to subscribe for the timeupdate event, but the result will upset you. It is triggered 4–5 times per second and we will just get a slideshow as a result of rendering.</p><figure><img alt="timeupdate event call frequency" src="https://cdn-images-1.medium.com/max/197/1*LKojec6ZY_QNQuT4lrA6vg.png" /><figcaption>timeupdate event call frequency</figcaption></figure><p>Our video plays at almost 30 frames per second. Yes, this is not what we expected, let’s try further.</p><p>Using a recursive call to requestAnimationFrame, we can more often (60 times per second in at best case) call a method that will receive the time on the video and determine the frame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d64c5d4ab38f4aff03fca9e9d9435e7b/href">https://medium.com/media/d64c5d4ab38f4aff03fca9e9d9435e7b/href</a></iframe><p>Now we have the “player” on the canvas. It remains to learn how to blur faces.</p><p>Options which we have for blur:</p><ul><li>Gaussian blur inside objects</li><li>Gaussian blur outside objects</li><li>Pixelate inside objects</li><li>Pixelate outside objects</li></ul><h3><strong>Gaussian Blur</strong></h3><p>To implement this case, we need 2 more canvases on top of the canvas with the rendered video frame. One is for blurring the entire canvas, the second for cutting out the necessary objects from the blurred canvas by coordinates.</p><figure><img alt="Layers with canvases for blur objects" src="https://cdn-images-1.medium.com/max/512/1*56YPsFQ6g4eceG-6DCQo0Q.png" /><figcaption>Layers with canvases for blur objects</figcaption></figure><p>Blurring the entire layer is easy. To do this, you need to apply a blur filter with a given intensity, in my implementation, it is 30. The brightness is used here in order to enhance the blur effect since for bright images you will still see too much of what is under the blur. Then all that remains is to draw our video frame on this canvas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0c3d1a1a1755a34c5ed78868b2e613c/href">https://medium.com/media/d0c3d1a1a1755a34c5ed78868b2e613c/href</a></iframe><p>Now we need to cut our objects by coordinates. We have data about all objects on each frame (with coordinates x, y, height and width, type of blur), so you just need to go through all these objects on the frame and do a little magic.</p><p>We form data about the area where the object is located.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca34434a01ba64144ed93a96bf7b21a/href">https://medium.com/media/4ca34434a01ba64144ed93a96bf7b21a/href</a></iframe><p>It will be a rectangle, but we need an ellipse … Okay, okay, everything will be done now.</p><p>With a little school knowledge, we get the radii in height and width and find the center of the ellipse. Draw ellipses and constrain their drawing areas using clip.</p><p>The last step. The drawImage method will take different layers depending on how we will blur (inside the object or outside). If we need to blur outside the object, we take the image from the video, if inside, we take from the blurred canvas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24280f4920656df5793ab0d67265a5cd/href">https://medium.com/media/24280f4920656df5793ab0d67265a5cd/href</a></iframe><p>You may have noticed that objects are sorted by the isBlurOut field for some reason.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f492bb9e90d6d4143731ee24f053ef39/href">https://medium.com/media/f492bb9e90d6d4143731ee24f053ef39/href</a></iframe><p>This is for the case when we have objects with an outer blur on the frame, and objects with an inner blur, and they intersect in some area. In order for an object with an inner blur to be over the image we first need to draw all objects with the outer blur, then draw objects with the inner blur over the image.</p><figure><img alt="Intersection of objects" src="https://cdn-images-1.medium.com/max/512/1*8D77KVpLCwlsKs-gDiaZXA.png" /><figcaption>Intersection of objects</figcaption></figure><h3>Pixelation</h3><p>Pixelation will be a little more difficult. Let’s first consider a case with pixelation inside an object. We also have 2 layers on top of the canvas with the rendered video. But there is also a small hack here.</p><p>On the layer where we blurred the entire canvas, now we reduce our image 12.5 times and paint it. There is a blurIntensity in the downsizeRatio formula so that we can decrease or increase the pixel size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10998372310240de670a3d23afef4b23/href">https://medium.com/media/10998372310240de670a3d23afef4b23/href</a></iframe><p>We get the following result</p><figure><img alt="Downsize image" src="https://cdn-images-1.medium.com/max/512/1*3pIQgABzXDeCtPhzJLYLNQ.png" /><figcaption>Downsize image</figcaption></figure><p>Now, when we go through all the objects in the frame, we will get this result, because we are drawing ellipses in real size, but we take the picture from the small image in the upper left corner. It turns out we stretch it and get a pixelated image.</p><figure><img alt="Get pixelate images" src="https://cdn-images-1.medium.com/max/512/1*O-ckksIaQp2QJKp75dTnWA.png" /><figcaption>Get pixelate images</figcaption></figure><p>It’s magic!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*4WTSQuPlmtR7rvPMyqNKXw.png" /></figure><p>It remains to consider the pixelation of the entire frame. This is a rather difficult operation, and it needs more than a couple of lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11b2ae837036ecd023a2e649da886934/href">https://medium.com/media/11b2ae837036ecd023a2e649da886934/href</a></iframe><p>You need to get the imageData from the canvas with the rendered video, it will be a huge array with the description of the image pixels. Every 4 elements in this array describe the RGBA of each pixel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ad0cb3dace2bcc450390d885a1927a9/href">https://medium.com/media/0ad0cb3dace2bcc450390d885a1927a9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*g-JVLDZZiTyr_RQEQ5skww.png" /><figcaption>ImageData array</figcaption></figure><p>That’s why pixelating the entire frame needs a lot of time.</p><p>But not everything is so bad, we do not need to go over this entire array. Depending on the pixelSize (the size of a pixel or in other words, how many pixels we want to combine into one rectangle), that much less we will have to traverse this array.</p><p>Running over each pixel that is a multiple of pixelSize, we calculate its position in the array with RGBA representation of the image using the formula:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bd208c08b32717f0513aaa36a7d2a70/href">https://medium.com/media/5bd208c08b32717f0513aaa36a7d2a70/href</a></iframe><p>And then we apply our change to the canvas by drawing that pixel with the pixelSize and it&#39;s color:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e4b3d8ceb7de4ac047efe1c49670731/href">https://medium.com/media/7e4b3d8ceb7de4ac047efe1c49670731/href</a></iframe><p>Do you remember we darkened the image with a filter for Gaussian blur? So, forget about this implementation :)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4543df20394faf320d647bc2af77b70a/href">https://medium.com/media/4543df20394faf320d647bc2af77b70a/href</a></iframe><p>When we try to pixelate with this implementation it takes a very long time, for one frame it takes some seconds, you can check it by clicking on the Pixelate with canvas filter button in the <a href="https://objects-blur-demo.vercel.app/">demo</a>.</p><p>But we will not give up on this, we had a little knowledge of CSS, so it’s time to apply it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0965cc7bc1a18d2fbbe943fc64bfc740/href">https://medium.com/media/0965cc7bc1a18d2fbbe943fc64bfc740/href</a></iframe><p>Applied :)</p><p>You can check the result in the <a href="https://objects-blur-demo.vercel.app/">demo</a> by clicking the Pixelate with CSS filter button. It will really surprise you.</p><h3>Conclusion</h3><p>Thank you for reading the article till the end. You can find the code on <a href="https://github.com/yantsishko/objects-blur-example">GitHub</a> and see the <a href="https://objects-blur-demo.vercel.app/">online demo</a>.</p><p>There is nothing impossible, it’s just a matter of time.</p><p>P.S. If anyone can tell me how to mix the colors of neighboring pixels when pixelating so that it is not so “rough”, I will be very grateful. OpenCV.js does not offer its overhead for an application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=898cddc01ae6" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-blur-objects-in-real-time-with-video-and-canvas-898cddc01ae6">How To Blur Objects in Real-Time With Video and Canvas</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[We Built a Face and Mask Detection Web App for Google Chrome]]></title>
            <link>https://yantsishko.medium.com/we-built-a-face-and-mask-detection-web-app-for-google-chrome-c2a22e97b0bf?source=rss-d4d014fc538c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2a22e97b0bf</guid>
            <category><![CDATA[image-detection]]></category>
            <category><![CDATA[face-mask]]></category>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[tensorflowjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yan Tsishko]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-06-29T07:24:18.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="face mask detection image" src="https://cdn-images-1.medium.com/max/1024/1*vhLYR1mkuPnCq7Aheo03_A.png" /></figure><h3>Introduction</h3><p>The main goal is an attempt to detect face and mask in the browser, instead of Python implementation at back-end. This application is a simple webapp / SPA application which contains JS code only and can send some data to a backend for next processing. But initial face and mask detection is done on the browser side, no Python backend implementation is needed.</p><p><em>At the current moment, the app works only in the Google Chrome browser.</em></p><p>In future articles, I will describe more technical details, the implementation of all our investigation results.</p><p>There are 2 approaches of how this can be done with browser implementation:</p><ol><li><a href="https://github.com/tensorflow/tfjs">TensorFlowJS</a></li><li><a href="https://github.com/microsoft/onnxjs">ONNXJS</a></li></ol><p>Both runtimes support WASM, WebGL, and CPU backends. But we will compare only WASM and WebGL, because CPU performance is very low and it can’t be used in production.</p><blockquote><a href="https://face-mask-detection-demo.vercel.app/"><em>View the demo here</em></a></blockquote><h3>TensorFlow.js</h3><p>At the official website, TensorFlow.js proposes some pre-trained and ready to be used models which includes the appropriate JS postprocessing. For real-time face detection, it is specified in the BlazeFace model, for which <a href="https://storage.googleapis.com/tfjs-models/demos/blazeface/index.html">an online demo is available</a>.</p><p>More info about BlazeFace can be found <a href="https://sites.google.com/view/perception-cv4arvr/blazeface">here</a>.</p><p>We created a demo to play a bit with the runtime and model, identify any existing issues. The appropriate links to run the app with different models can be found below:</p><p>WASM (face detection image size: 160x120; mask detection image size: 64x64px</p><ul><li><a href="https://face-mask-detection-demo.vercel.app/?mobileNetVersion=264&amp;mobileNetWeight=0.35&amp;backend=wasm">Blaze Face + MobileNet V2 0.35</a></li><li><a href="https://face-mask-detection-demo.vercel.app/?mobileNetVersion=264&amp;mobileNetWeight=0.5&amp;backend=wasm">Blaze Face + MobileNet V2 0.5</a></li><li><a href="https://face-mask-detection-demo.vercel.app/?mobileNetVersion=3S64&amp;mobileNetWeight=0.75&amp;backend=wasm">Blaze Face + MobileNet V3 0.75</a></li></ul><p>WebGL (face detection image size: 160x120; mask detection image size: 64x64px</p><ul><li><a href="https://face-mask-detection-demo.vercel.app/?mobileNetVersion=264&amp;mobileNetWeight=0.35&amp;backend=webgl">Blaze Face + MobileNet V2 0.35</a></li><li><a href="https://face-mask-detection-demo.vercel.app/?mobileNetVersion=264&amp;mobileNetWeight=0.5&amp;backend=webgl">Blaze Face + MobileNet V2 0.5</a></li><li><a href="https://face-mask-detection-demo.vercel.app/?mobileNetVersion=3S64&amp;mobileNetWeight=0.75&amp;backend=webgl">Blaze Face + MobileNet V3 0.75</a></li></ul><h3>Performance Results: Getting Frames</h3><p>We can get frames via the appropriate HTML API features. But this process frames consumes time as well. So we need to understand how much time we will spend on such activities. There are the appropriate timing metrics below.</p><p>Our goal is to detect faces as fast as possible so we should get each frame of the live stream and process. For this issue, we can use <strong>requestAnimationFrame</strong> which is called every 16.6ms or each frame.</p><p>Using <strong>grabFrame()</strong> method of the <strong>ImageCapture</strong> allows us to take a snapshot of the live video in a <strong>MediaStreamTrack </strong>and return a promise that resolves with an <strong>ImageBitmap</strong> containing the snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5-eNYCUkx5dj74PZlCg8w.jpeg" /></figure><p>Single mode it is max performance of getting frame. Sync mode it’s how often we can get frame with face detection.</p><h3>Face Detection + Mask Detection Results:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8EdBUA7P-85BlewmfCugBg.jpeg" /><figcaption>Color scheme: <strong>&lt; 6 fps</strong> red, <strong>7–12 fps</strong> orange, <strong>13–18 fps </strong>yellow, <strong>19+</strong> fps green</figcaption></figure><p><strong>Results:</strong></p><blockquote><em>We excluded timing metrics from the application start. It is obvious that during the application startup and first runs of the model it will consume more resources/time. When the app is in a warm mode it is worth getting performance metrics only. Warm mode in our case it is just let the app do work 5–10 sec and then get performance metrics.</em></blockquote><p>Possible inaccuracies in the gathered timings metrics are up to 50ms.</p><p>The BlazeFace model was developed especially for the mobile devices and helps to achieve good performance with the TFLite inference on Android and IOS platforms (~50–200 FPS).</p><p>Meanwhile the dataset for retraining the model from scratch is not available (Google Research Team did not share it).</p><p>So, there are two model types:</p><ul><li>Front: Input size 128 x 128px, faster but lower accuracy.</li><li>Back: Input size 256 x 256px, higher accuracy but slower.</li></ul><p>This means that the preparation of a detector model with three classes (clear face, face with mask, background) can be a time consuming task.</p><h3>Images Size</h3><p>The original image can be of any size according to the camera settings and business needs. But when we process the frames for face and mask detection the original frame is resized to the appropriate size depending on the model.</p><p>Image which is used by BlazeFace for face detection is specified with the size 128 x 128px. The original frame is resized to this size considering its proportion. Image which is used by mask detection is specified with the size 64 x 64px.</p><p>We chose the minimal resolutions for both images taking into account performance requirements and results. Such minimal images demonstrated the best performance results on PC and mobile devices. We use 64 x 64px for thumbnails to detect the mask because size 32 x 32px is not enough for mask detection with sufficient accuracy.</p><h3>How to Get the Best Images to be Analyzed by the Application</h3><p>With TensorFlow.js we have the following options to get the best images to be used in feature by the application:</p><ul><li>BlazeFace allows you to configure the score for the detected images. We will set this score to high value (&gt;0.9) to avoid any uncertain positives</li><li>BlazeFace allows you to configure a max amount of faces which are returned from the detection method. We can specify this option to 1 to return 1 face only; we can set it to 2 for example, and in case of 2 faces just to send a message that one person/face can be in front of camera only</li><li>BlazeFace returns bounding box and landmarks. According to the all-in-one device calibration we have all power in our hands to apply the appropriate checks for these results to be sure if the detected faces are in a good quality.</li></ul><p><strong>Such checks can be the following:</strong></p><ol><li>Bounding box should in the calibrated box in X%</li><li>All N or M from N landmarks should be in the calibrated box</li><li>Width and height of the bounding box should be above the appropriate thresholds</li><li>Checks with bounding boxes width/height and landmarks are extremely fast on the client side with JS</li></ol><p>The selected images according to the specified rules above will be sent to next stages of the pipeline: mask detection. Such logic will provide faster face detection results till the moment when we are sure that the detected face is in a good quality.</p><h3>Mask detection models sizes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5cKvXOam5Emzt2wG0DSVQ.jpeg" /></figure><p>For mask detection using trained <strong>MobileNetV2</strong> and <strong>MobileNetV3</strong> with different types and multipliers.</p><p>We tend to use light or ultra-light models with TensorFlowJS in the browser (&lt; 3Mb). The main reason is the fact that the WASM backend is faster with such models. It is specified in the official documentation and it is confirmed by our performance tests as well.</p><h3>Additional Resources</h3><ul><li>WASM JS back-end: ~60Kb</li><li>OpenCVJS: 1.6Mb</li><li>Our SPA itself (+Tensorflow.js): up to 500Kb</li><li>BlazeFace model is ultra-light: 466Kb</li></ul><p>For webapp time to interact (TTI) with ~3.5Mb of JS and binary + JSON of size from 1.5Mb to 6Mb (everything will be in internal network) will be &gt;10s in cold mode; in warm mode the expected TTI — 4–5sec.</p><p>If it is used by web worker(s) and OpenCV.js is used in the worker(s) only it will significantly reduce the size of the main app with 800–900Kb JS, TTI will be 7–8s in cold mode; in warm mode — &lt;5s.</p><p><strong>Possible approaches to run neural network models in browser:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKg6jZbGQb_dHwUf-yxI3w.jpeg" /><figcaption><em>One thread implementation</em></figcaption></figure><p>It is a default implementation for browsers. We run both models for face and mask detections in one thread. A crucial point is to provide a good performance for both models to be run with any issues in one single thread. It is the current approach which was used to take the performance metrics above.</p><p>This approach has some limitations. If we would like to add additional models to be run in the pipeline they will be run in the same thread in async way but in sequential flow. It will decrease total performance metrics regarding frames processing.</p><p><em>Web Worker(s) usage to run models in different context and have parallelism in the browser:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmocROf4MkhHpuYOtTFNHg.jpeg" /></figure><p>It is used in the main JS thread to run BlazeFace model for face detection, but mask detection is running in a separate thread via web worker. With such implementation we can separate both models running and introduce parallelism for processing in the browser. It will have a positive influence on general UX feeling with the application. Web workers will load TFJS and OpenCV libraries, main JS thread — TF.JS only.</p><p>It means that the main app will start much faster and by doing it we can significantly reduce TTI time in the browser. Face detection will start more often, it will increase the FPS of the face detection process. As a result mask detection process will be run more often as well and FPS of this process will be increased as well. The expected improvements are up to ~20%. It means that the FPS and MS specified in the article above can be improved by this value.</p><blockquote><em>With such an approach to run different models in separate contexts via web workers we can run more neural network models in the browser with good performanсe. The main factor here will be all-in-one device hardware characteristics to support such loading.</em></blockquote><p>We have implemented such an approach in the app and it works. But we have some technical issues with postMessage callback when a web worker sends a message back to the main thread. For some reasons it introduces additional delay (up to 200ms on mobile devices) which kill the performance improvement which we achieved with parallelism (this issue actual only for vanilla JS, after implementation in React this issue was fixed)</p><h3>Web Worker Investigation Results</h3><p>Our idea is to use web workers (WW) to run every model in a separate worker/thread/context and achieve model processing parallelism in the browser. But we noticed that the callback function in WW is called with some delays. Below you can find the appropriate investigation measurements and conclusions on what factors it depends on.</p><pre>Test params:<br>mobileNetVersion=V3<br>mobileNetVersionMultiplier = 0.75<br>mobileNetVersionType = float16<br>thumbnailSize=32px<br>backend = wasm</pre><p>In the app we run BlazeFace in main thread and mask detection model in web worker.</p><p>Here are some measurements for WW processing time on different devices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHNS_JOEIHUCqq7E2_XNCQ.jpeg" /><figcaption>Laptop, MacOS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1B2vxYgmmSLU7QyIgpq1w.jpeg" /><figcaption>Laptop, Windows</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFi6AgreYzAdC5BKTaiVEQ.jpeg" /><figcaption>Phone, Android</figcaption></figure><p>The results above demonstrate that for some reasons time to send a callback from Web Worker to the main thread depends on the model running or using TensorFlow method <strong>browser.fromPixels</strong> in this Web Worker.</p><p>If it is run with a model the callback on MAC OS is sent ~27ms, if model is not run — 5ms. This difference on MAC OS in 22ms can lead to 100–300ms delays on more weak devices and it will have an effect on general app performance with Web Worker usage.</p><p>Currently we don’t understand why it happens but we know the fact that it has happened.</p><h3>How to Increase Accuracy, Decrease False Positives, Run Access Control API for Stable Faces Only</h3><p>We need to have more “context” to take the appropriate decision to inform to face detection and removing mask . Such context is the prev processed frames and their state (is face or not, is face or not, is mask or not). We implemented a “flying” segment to manage such additional context. The length of segment is configurable and depends on the current FPS, but in any case it should not be more than 200–300ms to not introduce visible delays.</p><p><em>Below is the appropriate scheme which describes the idea:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeHbekxGg8nEZPCPqa20gA.jpeg" /></figure><h3>Conclusions:</h3><p>As stronger device we have as better performance results regarding taking metrics it is demonstrated:</p><p>For PC we could get the following metrics:</p><ul><li>Face detection only: &gt;30fps</li><li>Face detection + mask detection: up yo 45fps</li></ul><p>For mobile devices we could get the following metrics:</p><ul><li>Face detection only: from 2.5fps to 12–15fps depends on mobile devices</li><li>Face detection + mask detection: from 2 to 12fps depends on mobile devices</li></ul><ol><li>Pay attention that video is always real-time and its performance depends on device itself, but it always will be from 30fps.</li><li>For mask detection model for the most cases the best results are demonstrated by MobileNetV2 0.35 model, types don’t influence the performance metrics with visible effect.</li><li>Size of the mask detection model depends on types. Since types don’t influence performance metrics it is recommended to use uint16 or float16 models to have less model size in the browser and as a result faster TTI.</li><li>WASM runtime demonstrates better results in comparison with WebGL for BlazeFace model. It is correlated with the <a href="https://blog.tensorflow.org/2020/03/introducing-webassembly-backend-for-tensorflow-js.html">official TensorFlowJS documentation regarding performance of small models (&lt; 3Mb)</a>: For most models, the WebGL backend will still outperform the WASM backend, however WASM can be faster for ultra-lite models (less than 3MB and 60M multiply-adds). In this scenario, the benefits of GPU parallelization are outweighed by the fixed overhead costs of executing WebGL shaders.</li><li>TTI time is always better for WASM models in comparison with webgl with the same models configuration.</li><li>The performance of TensorFlowJS runtime and models can be increased by using <a href="https://github.com/WebAssembly/simd">WASM extension</a> to add <a href="https://en.wikipedia.org/wiki/SIMD">SIMD</a> instructions allowing multiple floating point operations to be vectorized and executed in parallel. Preliminary tests show that enabling these extensions brings 2–3x speedup over WASM today.</li><li>More info is <a href="https://blog.tensorflow.org/2020/03/introducing-webassembly-backend-for-tensorflow-js.html">here</a>. It is still an experimental feature which is not delivered with the runtime by default. Also after the release it will be available in the runtime by default or via additional configuration options.</li><li>On the client side the expected size of the app is ~3.5Mb of encoded JS with all dependencies, 466Kb of BlazeFace model, from 1.1Mb to 5.6Mb of mask detection model. The expected TTI time for the application is &gt;10sec for mobile devices in cold mode; in warm mode — ~5sec.</li><li>With web workers usage OpenCV.js can be loaded into web workers only, it significantly reduce TTI for the main app.</li><li>During our testing we noticed that the devices were very hot. Since it is expected 24/7 availability of the solution this fact can have a big influence on the final decision which devices to use. You need to take this information into account.</li><li>It is also was noticed that it is better if devices are fully charged and they are connected to the charger during working. In this case the performance of devices according to our observations is better. Charging from USB doesn’t allow to support battery on the same level in a long perspective, it should be used for electric charging. This information should be taken into account.</li><li>In our view even 4–5 fps are enough for the current solution to provide good UX user perception. But it is important to not show bounding boxes or landmarks on the screen, but operate the whole video/screen size:<br>Highlight screen when we captured person.<br>Inform about mask / no mask factor via text messages or another highlighting of the screen.</li><li>With such a user interacting the delays between realtime and our metadata on the screen will be 200–300ms. Such values will be considered by users of the system as non-critical delays.</li></ol><p><em>Originally published at </em><a href="https://hackernoon.com/we-built-a-face-and-mask-detection-web-app-for-google-chrome-836n33aq"><em>https://hackernoon.com</em></a><em> on March 7, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2a22e97b0bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>