Zhongde Liu

This is my personal "Clipboard" of web development stuff I come across

Leave a comment

Polyfill of some array ES5 functions

I collected the most used ES5 array methods as a polyfill for older browsers (IE …).


Based on the great reference at MDN Arrays, it has fallbacks for
Array.every, Array.some, Array.filter, Array.forEach, Array.indexOf, Array.reduce.

To install / use it you either can clone the github repository or fetch it via Bower. Then include it per script tag, before your scripts.

Leave a comment

Code: “cast a number to int” with bitwise operators

In order to cast a number to an int value you can also use bit operations. In particular the Double NOT and the OR 0.

~~(3.14) // => 3
3.14 | 0 // => 3

As these operations are working on on signed 32-bit integers per default, the number is in fact truncated after the comma. This also works on negative numbers.

~~(-3.14) // => -3
-3.14 | 0 // => -3

You are asking Why? Why should anyone bother bitwise operators? one word: Performace. If you are crunching a lot, I mean, a lot, numbers, you should notice something. I made a quick jsperf http://jsperf.com/parseint-and-bitwise-operations. You see the bit operations are more than 10x faster than parseInt.

Sidenote: Math.floor is also pretty fast. However Math.floor results in a different result number when used with negative ones.

Math.floor(-3.14) // => -4

Leave a comment

Code: load handler with cached images and IE

Just had a strange case, that the load event of an image is not fired. After a short research I found the issue…

Not working code:
$('img').attr('src', 'image.jpg').load(function() {
//Do something - but it doesn't

Working code:
$('img').load(function() {
//Do something - it does
}).attr('src', 'image.jpg');

The thing is IE (and Opera) will load the cached image directly before your event handler is attached…

It is jQuery Notation but also applies to Vanilla JS.

1 Comment

Reference: Google Code Styleguides

Reference Styleguide for different languages from Google


from the Page:

google-styleguide – Style guides for Google-originated open-source projects

“Style” covers a lot of ground, from “use camelCase for variable names” to “never use global variables” to “never use exceptions.” This project holds the style guidelines we use for Google code. If you are modifying a project that originated at Google, you may be pointed to this page to see the style guides that apply to that project.