{{announcement.body}}
{{announcement.title}}

Let's Chunk - Part Two

DZone 's Guide to

Let's Chunk - Part Two

In this post, we take a look at how to use the chunk function in JavaScript. Don't worry, it's not as gross as it sounds.

· Web Dev Zone ·
Free Resource

In my previous article, we talked about the chunk function and implemented it in JavaScript. Today I’ll try to show an example for using this function. This example popped into my mind when I read about the chunk function, because it reminded me of a question I once gave to my students in an exam, and I think the chunk function could have been helpful for them had they known it.

The task goes like that – write a function called printWithCommas. The function would get two integers – num and d. The function would return a string that represents num with a comma after every d digits from the right. It is possible that the last leftmost part wouldn’t contain exactly d digits, according to d and the total digits in the number.

For example, if num was 12345678 and d was 3 the output would have been 12,345,678. And for the same num, if d was 2 the output would have been 12,34,56,78.

It’s not a very complicated problem, but it does have a twist because the only group of digits that can contain less than d digits is the leftmost one, but because of the nature of reading numbers, we usually start reading the number from right to left, using the modulo operation, such as num % 10 to get the last digit.

Now when I thought about the chunk function it suddenly occurred to me that the number is divided into chunks of d digits. So the chunk function may be used here.

OK, I’ll say in advance – it’s a long shot and I guess solving this problem without the chunk function is not that difficult, and we do have to do some pre-processing before the chunk function can kick in, but I think it’s a good practice and demonstration of solving a problem in a creative way using existing tools.

To solve this problem we first have to convert the number into an array because the chunk function works on arrays. So after splitting the number into an array, the number 12345678 would yield the array [8, 7, 6, 5, 4, 3, 2, 1]. Note that the digits are in reversed order.

Now we can chunk them in chunks of d elements, using the chunk function. Note that according to the chunking algorithm, the last chunk can be with less than d elements, exactly as we defined in the question. For example, after chunking this array with d = 3 we’ll get the array – [[8, 7, 6], [5, 4, 3], [2, 1]].

We should output the digits with a comma between each chunk. But we should start printing the last chunk first, so let’s reverse the array and get – [[2, 1], [5, 4, 3], [8, 7, 6]].

Now it’s pretty easy – for each sub-array in the array, print its elements and then print the comma. Note that since the digits are in reversed order, we’ll print each sub array from end to start.

This is the code:

function printWithCommas(num, d) {

    var numArr = [];

  // convert num to array
    while(num != 0) {
        numArr.push(num % 10);
        num = Math.floor(num / 10);
    }

    var res = "";

    // create chunks of d elements each
    var chunks = chunk(numArr, d).reverse();

    // concat each chunk with a comma separator
    chunks.forEach(function(chunk, ind) {
      chunk.reverse().forEach(x => res += x);
         if(ind < chunks.length - 1)
                res += ",";
    });

    return res;
}

Was it worth it? I don’t know, it is probably overkill for this problem. Nonetheless, I think the solution is creative and elegant because it contains the essence of solving problems – it takes the given problem and transforms it to another one because we have a given solution to the other one.

What do you think?

Topics:
chunck function, javascript, javascript functions, javascript tutorials, web dev

Published at DZone with permission of Shay Tavor . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}