Everyone Can Code!

JavaScript Kata #11: Square Every Digit

By YayoDrayber | Learn To Code With Me | 14 Aug 2022


If you missed the introductory post, it's here. For a list of previously solved katas, please refer to the bottom of this page.

If this is your first time seeing my post, please note - these katas are probably randomly assigned per user so please don't go into Codewars thinking we will have exactly the same user experience, I am just posting these in the order that I got them.

Kata #11

DESCRIPTION:

Welcome. In this kata, you are asked to square every digit of a number and concatenate them.

For example, if we run 9119 through the function, 811181 will come out, because 9^2 is 81 and 1^2 is 1.

Note: The function accepts an integer and returns an integer

Starting code:

function squareDigits(num){
  return 0;
}

My attempt that worked:

function squareDigits(num){
  let numToArr = Array.from(num.toString())
  let strHolder = ""
  for (i=0;i<numToArr.length;i++){
    strHolder += (numToArr[i]**2)
  }
  return Number(strHolder);
}

The challenges before this one were at 8 kyu rank, this is the first 7 kyu problem that I got.

Rank #1 'Best Practice':

function squareDigits(num){
  return Number(('' + num).split('').map(function (val) { return val * val;}).join(''));
  
}

Rank #2:

function squareDigits(num){
  return +num.toString().split('').map(i => i*i).join('');
}

Rank #3 which shows how to do it with the parseInt() function:

function squareDigits(num){
  var array = num.toString().split('').map( function(int) {
    var i = parseInt(int);
    return i * i;
  });
  
  return parseInt(array.join(""));
}

Rank #4 where I think my approach kinda sorta falls under, except I didn't use the .join() method:

function squareDigits(num){
    var string = num.toString();
    var results = [];
    for (var i = 0; i < string.length; i++){
        results[i] = string[i] * string[i];
    }
    return Number(results.join(''));
};

That's it for Kata #11, stay tuned for more katas to be solved!

Link to Kata #1: Square(n) Sum

Link to Kata #2: Convert a Number to a String

Link to Kata #3: DNA to RNA Conversion

Link to Kata #4: Remove First and Last Character

Link to Kata #5: MakeUpperCase

Link to Kata #6: Total amount of points

Link to Kata #7: A Needle in the Haystack

Link to Kata #8: Sum of positive

Link to Kata #9: Basic Mathematical Operations

Link to Kata #10: Beginner - Reduce but Grow

How do you rate this article?

3


YayoDrayber
YayoDrayber

A Yayo, A Drayber, among others.


Learn To Code With Me
Learn To Code With Me

Just started with Codewars and will be posting the solutions I came up with here and the apparent best practices.

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.