Total results: 26

Fastest alternative to Math.floor in JavaScript

Normally to floor a number in JavaScript we would use the built in Math.floor function. There are however other ways to round a number down in JavaScript, by using the bitwise operators to perform the rounding operation on a binary level.

The various methods are:

  • |
  • ~~
  • <<
  • >>
  • >>>

Which can be used, for example, like so:

var float = 367.9987;

~~float //367
float | 0 //367
float << 0 //367
float >> 0 //367
float >>> 0 //367

I have set up a test on the great JS Perf website to sample which of these methods is fastest in the various browsers, check out the result and run the tests for yourself here:

http://jsperf.com/math-floor-alternatives

So far, my result graph looks like so (for an interactive version please visit the link above):

Math.floor results in JavaScript (from Browserscope)

These results are very interesting. As you can see currently Chrome will handle all of these operations at almost the same speed. However, Internet Explorer handles Math.floor around 76% slower than a bitwise shift/or.

Surprisingly Safari 7 handles all versions in a slow manner, with the triple bitwise shift (>>>) being the fastest.

In FireFox Math.floor has actually been optimised to the fastest but the other methods are still very close behind.

Taking all of this into account, I would suggest using a regular bitwise shift >> as this is fast in all browsers, including Internet Explorer.

However, that being said the syntax for a bitwise not is more intuitive and looks more natural in the flow of code, for example:

var x = 345.768,
  y = 0;

// Confusing
y = (5 * x) << 0;

// Nicer
y = ~~(5 * x);

// Least confusing, but slower
y = Math.floor( 5 * x );

So ultimately you must make the choice of which operation to use based on your application, the audience you have and the actual routine you are implementing. Meaning, it's best not to confuse the next programmer who comes along so Math.floor is best in non performance critical code but (5 * x) << 0; might be a good idea in a performance bottleneck situation such as on an animated <canvas> which runs code in a loop many times per second.

Thanks for the programming challenge, Deutsche Telekom!

A guide on how to fix the Speedport W 723V "web 'n' walk" configuration error that occurs when trying to run the setup.

Recently the W 723V Speedport router that I rent from Deutsche Telekom automatically pulled an update for new software. This update put my router into an unresponsive mode, meaning I had to reset the device and re-enter my login / configuration data through the internal configuration utility (A.K.A https://speedport.ip/).

The Speedport provides a configuration page where I would normally enter my Deutsche Telekom details and the setup would run. After this update however, the setup tells me that my "Web 'n' Walk Stick" has not been properly configured.

I do not own a Web 'n' Walk stick, so I saw this as an obvious bug in the configuration web page. The page was submitting the wrong configuration form details, as both forms are in the same page, just shown/hidden via JavaScript.

After calling Deutsche Telekom, they were clueless, had no help to give and promised to call back when an engineer was available. This is where I took the task upon myself to inspect the router software and see if I could fix this problem myself. The game was afoot, a programming challenge lay ahead. After around an hour absorbed in convoluted code, ignoring the temptation to let the Deutsche Telekom get away with this, I focused in on the problem, the following is the description of the solution.

Swipe.JS - Detect touch direction and distance

During development of recent project, I have had to realize a JavaScript solution that will detect when a visitor swipes the page and then perform an action based on the swipe direction and distance.

Of course this is not a new challenge and many solutions have already been found. jQuery mobile ships with a built in swipe event but I did not require such an extensive framework and decided to write the cleanest answer that solved the problem.

Below you will find the source code to a jQuery plugin I call "Swipe.JS", which provides the same swipe event to any DOM node.

Usage

First I will show how to use the plugin. Multiple swipe events can be bound to different nodes but for the sake of example, we will use the "body".

$("body").swipe(function( direction, offset ) {
  console.log( "Moving", direction.x, "and", direction.y );
  console.log( "Touch moved by", offset.x, "horizontally and", offset.y, "vertically" );    
});

Swipe.JS console output

Static file web servers

Testing a static website can be done simply by opening the HTML files in a web browser, but for some functionality to perform correctly, such as local AJAX calls, the files need to be served from a web server.

Alternatively, you may want to check out some static files on your mobile device. You can do this easily by starting a simple web server for the project and navigate to your computers IP address with the given server port.

Python Server

The easiest way to do this on UNIX based systems is to use the Python Simple HTTP Server, like so:

python -m SimpleHTTPServer 8080

Run this command in the same directory as your project from the terminal, then point your browser to http://localhost:8080.

This is a great way to get a server running in seconds, for basic testing, but I have found that as the number of files in the project increases, the stability of the server decreases. Often files will not be passed to the client and 404 errors are encountered. For these reasons I have investigated a stronger solution that is still simple to setup. This leads me to Node.JS.

Node Server

Node.JS is no stranger to web servers, in fact this is often the primary task of a Node application.

"Connect" is a Node.JS middleware application that makes the creation of simple web servers trivial.

To get Connect running, first install it via npm:

npm install -g connect

Here is a web server that can be used, simply paste the code into a file called "server.js" in your project's root directory.

var connect = require( 'connect' ),
  http = require( 'http' );

app = connect()
  .use( connect.logger( 'dev' ) )
  .use( connect.static( __dirname ) );

http.createServer( app ).listen( 8080 );

Finally run the server from the terminal like so:

node server.js

If no error was received, the server is running and files can be viewed by browsing http://localhost:8080, just like in the Python example.

I have not had any trouble with the Connect version of my server and it comes built with a nice development logger, showing what files were requested and with what status. This output can be viewed live in the terminal window as requests come in.

Connect Server Dev Log

Improve page performance with optimal CSS

There are certain CSS best practices that should be followed in order to increase CSS performance in the browser. These will help the browser to perform less DOM parsing and reduce the time of repaint events.

1. Browser reflow and repaint

If you are unfamiliar with the concepts of reflow and repaint, here are some articles that will get you up to speed:

2. Remove unused styles

Simply having styles that aren't used causes the browser to search the DOM for matches needlessly. This is wasted processor time. Additionally, the CSS file will have a higher page weight that is needlessly sent over the wire to the client.

It may not seem to make a huge difference but removing dead CSS code will greatly increase performance and additionally improve the project stability and maintainability.

Check size of localStorage usage in Chrome

localStorage is a great tool for JavaScript developers to persist information across multiple sessions. Due to its simple API, large browser support and and higher reliability than cookies, it can easily lead to the situation of overusing localStorage.

Since localStorage has a maximum size of 5MB the following snippet will help inspect what localStorage keys are being used and how much size is being allocated to each.

To give credit, I have taken the method here and added a total counter.

var total = 0;
for(var x in localStorage) {
  var amount = (localStorage[x].length * 2) / 1024 / 1024;
  total += amount;
  console.log( x + " = " + amount.toFixed(2) + " MB");
}
console.log( "Total: " + total.toFixed(2) + " MB");

Simply run this in the Chrome console or create a bookmarklet from the following code (Right click bookmark bar > Add Page > Copy the code as "URL")

javascript:var total = 0;for(var x in localStorage) {  var amount = (localStorage[x].length * 2) / 1024 / 1024;  total += amount;  console.log( x + "=" + amount.toFixed(2) + " MB");}console.log( "Total: " + total.toFixed(2) + " MB");

Which will give a similar output:

Matches = 0.40 MB
Matches_timestamp = 0.00 MB
Teams = 0.19 MB
Teams_timestamp = 0.00 MB
Total: 0.59 MB

Dynamically append LESS.js stylesheets

Here is a function that can be called to dynamically apply a LESS.js stylesheet to the DOM after the page has finished loading. The following code snippet uses jQuery for convenience.

 function loadLESS ( filename ) {
    // If LESS isn't available, do nothing
    if ( !window.less ) { return;}

    // Create LESS link and add to <head>
    var $link = $("<link type='text/css' rel='stylesheet/less' />");
    $link.attr("href", filename + ".less");
    $("head").append( $link );

    // Notify LESS that there is a new stylesheet
    less.sheets.push( $link[0] );
    less.refresh();
}

The important parts are after applying the new link tag to the head section, the raw DOM node $link[0] must be added to the less.sheets array and then refresh called to apply the changes to the web page.

Also remember that the rel attribute for the link tag must be set to "stylesheet/less" rather than just "stylesheet".

Append an HTML string to the DOM without a JavaScript Library

In the event where appending new nodes to the DOM via JavaScript is required but there is no access to a library such as jQuery or Prototype.JS, this handy snippet allows an easy librabry-like API with a tiny amount of code:

 function append ( elString, parent ) {
    var div = document.createElement( "div" );
    div.innerHTML = elString;
    document.querySelector( parent || "body" ).appendChild( div.firstChild );
 }

This snippet can be used easily:

// Append a link tag to the head
append( "<link rel='stylesheet' href='css/foo.css' />", "head" );

// Append a parapgraph to the body
append( "<p>My text</p>" );

// Append a new list item
append( "<li>Cheese</li>", "ul.shopping-list" );

© Blake Simpson, 2012 – 2017