JS rounding numbers

I have a requirement to be able to round numbers to either a whole number or to a specified number of decimal places….

Every now and then i find myself looking over my current solution to a problem when applying it in a new project. In this case it was very simple statistics and mean values.

For example:

const dec = [2, 678, 65.67467, 10.5452453453, 1, 0];
// Required outcome to 3 decimal places
// 2, 678, 65.675, 10.545, 1, 0

// Or to 2 decimal places
// 2, 678, 65.67, 10.55, 1, 0

My solution:

const round = (n, decimal = 2) => {
    return Math.round(n * Math.pow(10, decimal)) / Math.pow(10, decimal);
};
// Quick test
dec.forEach(n => {
console.log(round(n, 3));
});

dec.forEach(n => {
console.log(round(n));
});

As an aside: I need to have a set of numbers rounded and set with 2 fixed decimal places. So the same data set would be:

const dec = [2, 678, 65.67467, 10.5452453453, 1, 0];

// Required response would be
// 2.00, 678.00, 65.67, 10.55, 1.00, 0.00

There is the Number.toFixed() method

dec.forEach(n => console.log(n.toFixed(2)));

Finding, replacing, deleting and adding to a nested collection

Problem: I have an object that has a field call modules that is and array of activities. Activities is itself a complex and many nested object. I need to hunt for activities by their IDs and replace, delete or insert between existing objects

// Replace object in collection
Object.keys(data.modules).forEach(modKey => {
  Object.keys(data.modules[modKey].activities).forEach(activityKey => {
    if (data.modules[modKey].activities[activityKey].id === newActivity.id) {
      data.modules[modKey].activities.splice(activityKey, 1, newActivity);
    }
  });
});
// Remove object in collection
Object.keys(data.modules).forEach(modKey => {
  Object.keys(data.modules[modKey].activities).forEach(activityKey => {
    if (
      data.modules[modKey].activities[activityKey] &&
      data.modules[modKey].activities[activityKey].id === newActivity.id
    ) {
      data.modules[modKey].activities.splice(activityKey, 1);
    }
  });
});
// Insert object at index
const moudleIndex = 0;
const activityIndex = 2;

Object.keys(data.modules).forEach(modKey => {
  if (modKey == moudleIndex) {
    Object.keys(data.modules[modKey].activities).forEach(activityKey => {
      if (activityKey == activityIndex) {
        data.modules[modKey].activities.splice(activityKey, 0, newActivity);
      }
    });
  }
});

REGEX 2

Okay in the previous post we had found the “find” tool and realised we can do so much more with it using regular expressions (regEx).

To recap a regEx is

“a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text.”

\d = a character 0 to 9

\w = any character a to Z and 0 to 9

\s =  whitespace

Example:

\d\d\d will (using the find tool in your text editor) will highlight groups of 3 numbers in a string

\w\w\w\w\w will highlight groups of 5 characters

Notice how \w\w\w included numbers and letters

\s\s will highlight double spaces

Lets look for words that have only 4 characters.

A 4 letter word can be described as,

“a space followed by any 4 characters, followed by a space”

\s\w\w\w\w\s

Which can be rewritten as

\s\w{4}\s

But that will also include numbers. To ignore numbers

\s\w{4}[a-z]\s

Not quite there, if you are playing along you will notice that we are highlighting 4 letter words and the space before and after. What we need is to set boundaries.

\b\w{4}[a-z]\b

\b is a boundary, there are a few but for now lets stay with ‘spaces’. So with that you can find all four letter words

REGEX 1

Part 1 of understanding regular expressions (regEx).

RegEx is not just useful when writing code ( across different languages they are broadly similar) but I have found knowing a bit allows me to quickly become a “power user” when using the find replace functions in text editors like VSCode and PHPStorm.

If you are using VSCode bring up the “find” box and have a look for the icon .*

So instead of just searching for a text string you can quickly scan more accurately.

JavaScript fetch()

In a previous post I was refreshing my memory with vanilla JavaScript  after years of jQuery-ing, especially AJAX request and the

XMLHttpRequest()

My eyes rolled when I was reading more about it then  I found fetch()  ( I know its been about since 2015 and now almost universally adopted).

Fetch does what XMLHttpRequest does but in a more elegant way and DOES NOT need additional libraries as it is bundled with JavaScript. It also makes use of “promises” .

const url = "https://randomuser.me/api/?results=10";

fetch(url)
.then(function(response) {
 return response.json();
})
.then(function(data) {
 console.log(data.results);
})
.catch(function() {
 console.log("Booo");
});

The above code queries the URL, then parses the string as JSON, then does something with the data.

It also catches errors.

Good eh?

Its looks to be easy to expand and do all manner of fetching. For example submitting a form

var form = new FormData(commentForm);
fetch( url, { method: "POST", body: form })

You can then chain .then() promises to get the desired outcomes.

For more information

A quick introduction video from Google

From Google Working with the Fetch API

Jake Archibald’s post Thats so Fetch

Scotch post The Fetch API

New querySelector() and querySelectorAll()

Catching up with JavaScript after years of using jQuery I found these two shortcuts for replacing longer getElementById() methods. NOTE: the querySelector is passed an ID in the CSS format

<button id="our-button">Add New Item</button>

<script>
    // These are both the same
    var ourButton = document.getElementById("our-button");
    var ourButton = document.querySelector("#our-button");
</script>
<ul id="our-list>
    <li>A thing</li>
    <li>Another thing</li>
    <li>A new thing</li>
</ul>


<script>
// These are both the same
   var listItems = document.getElementById('#our-list').getElementsByTagName("li");
   var listItems = document.querySelectorAll("#our-list li");
</script>

 

 

Javascript AJAX without jQuery

I learnt this stuff years ago but with the rise of jQuery I like many others had become lazy. Add the fact that so many browsers handled things slightly different going down the library route had its benefits.

It is 2017 and things have improved many jQuery(ish) approaches have been adopted by Javascript and browsers have become more similar.

So here goes. First off a GET request to retrieve a Chuck Norris joke

<script>
var url = "http://api.icndb.com/jokes/random";
var request = new XMLHttpRequest();

request.open('GET', url, true);

request.onload = function() {
 if (request.status >= 200 && request.status < 400) {
 // Success!

printJokes(request.responseText);

} else {
 // We reached our target server, but it returned an error
 console.log('There was a problem. Status:' + request.status);

}
};

request.onerror = function() {
 console.log('There was a problem!');
};

request.send();


var printJokes = function(jokes){

JSON.parse(jokes, (key, value) => {
 key == 'joke' ?
 console.log(value) : ''
 });

}
</script>