Monday, July 8, 2019

jQuery autocomplete table

Jquery allows us to build really beautiful autocomplete box. For example, my task recently was to create a table-view autocomplete. That's what I made:



You can try it on JSFiddler:
https://jsfiddle.net/AndrewBuntsev/8jbqyrv4/

Thursday, June 20, 2019

Array.prototype.map(parseInt) tricky question

When I ran the following JS
['1', '7', '11'].map(parseInt);
I surprisingly saw the result [1, NaN, 3] instead of [1, 7, 11]. But if we try parseFloat
['1', '7', '11'].map(parseFloat);
the result is correct [1, 7, 11]
If we try the extended form of parseInt
['1', '7', '11'].map(i => parseInt(i));
we get the proper outcome as well.

So why is it so messy with the short parseInt?

Sunday, May 26, 2019

JavaScript string memory leak

If you create the following HTML file
<html>
  <body>
    <script>
      function createString() {
        return "0".repeat(25 * 1024 * 1024).substring(0, 12);
      }

      var arr = [];

      setInterval(function() {
         let str = createString();
         arr.push(str);
      }, 500);
    </script>
  </body>
</html>
run it in your browser and open the task manager you could notice that the browser takes some limited amount of memory ~200Mb. But what if we update one single digit in our code
return "0".repeat(25 * 1024 * 1024).substring(0, 13);
i.e. replace 12 with 13, run it into a browser and have a look at the process memory. It grows unstoppable and makes the browser crash in a half a minute! Why does it happen?

Every time we call String.prototype.substring function it returns new string instance that keeps .. a link to the original string! That's how V8 organizes memory for strings for permamance reason. Exception is when a new instance string length is less than 13 - in that case no link to original string preserved. So in our example arr contains no just short strings(13), but actually the huge ones (25 * 1024 * 1024). How to avoid it? Unfortunatelly, there is no documemnted method to 'cut' parents from strings, that's because we can do the following (update line 11):
<html>
  <body>
    <script>
      function createString() {
        return "0".repeat(25 * 1024 * 1024).substring(0, 12);
      }

      var arr = [];

      setInterval(function() {
         let str = createString().split('').join('');
         arr.push(str);
      }, 500);
    </script>
  </body>
</html>
That manoeuvre breaks the link with the original string and prevents memory leak.

Wednesday, May 15, 2019

Install NodeJS onto Ubuntu

The task sounds quite simple, but after I failed to do it several times I discovered that would be good to make a post about it. Just to have a step-by-step guide to save time when I decide to do it next time.

Firstly, let's remove old Node leftovers from previous installations
~$ sudo apt remove node
~$ sudo apt remove nodejs

and remove the node folder as well
~$ rm -rf node_modules/

That's time to download and install it in appropriate way. 

Sunday, May 5, 2019

React Tooltip Component published in NPM

Tooltip could be create with pure CSS, that's the example:
Such an awesome tooltip!

https://jsfiddle.net/AndrewBuntsev/jxk75o6c/

But I decided to go further and create a react component and publish it at NPM so that it could be reusable it other applications. That's the component HOC function implementation:

Saturday, April 20, 2019

React Lazy Routing

React routing is pretty straightforward and well documented feature. The example of usage is here
https://jsfiddle.net/AndrewBuntsev/3n5rmL0o/

If we need to load components only when they are needed we can utilize the code splitting techique with lazy() function and Suspense component

lazy() function loads the component no earlier than it is required
  
const Users = React.lazy(() => import('./Users'));

Suspense displays a loading component
  
render(
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <Users />
      </Suspense>
    </div>
  );

Tuesday, March 12, 2019

Upload Video in chunks with preview and progress bar using JavaScript

So, we have 3 following goals here:
  1. Preview video before it is uploaded
  2. Upload video file in small chunks
  3. Display a progress bar
All these tasks are achievable with JS and jQuery without any other libraries.
For choosing a video file we will use the standard input element
<input type="file" id="uploadVideoFile" accept="video/*" />
So to access the chosen file we will call
var fileInput = document.getElementById("uploadVideoFile");
To display video we need a video element
div id="videoSourceWrapper">
   <video style="width: 100%;" controls>
      <source id="videoSource"/>
   </video>
</div>
The following snippet displays the video after it is chosen in the video element for preview
$('#uploadVideoFile').on('change',
    function() {
        var fileInput = document.getElementById("uploadVideoFile");
        console.log('Trying to upload the video file: %O', fileInput);

        if ('files' in fileInput) {
            if (fileInput.files.length === 0) {
                alert("Select a file to upload");
            } else {
                var $source = $('#videoSource');
                $source[0].src = URL.createObjectURL(this.files[0]);
                $source.parent()[0].load();
                $("#videoSourceWrapper").show();
            }
        } else {
            console.log('No found "files" property');
        }
    }
);


As you can see, you can watch any video file having all necessary controls in the video player. Now let's have a look how to upload the video on your server.