Blog Spot!


7 Essential JavaScript Functions

I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent. Times have changed but there are still a few functions each developer should have in their arsenal, for performance for functional ease purposes.

debounce

The debounce function can be a game-changer when it comes to event-fueled performance. If you aren't using a debouncing function with a scroll, resize, key* event, you're probably doing it wrong. Here's a debounce function to keep your code efficient:

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

// Usage
var myEfficientFn = debounce(function() {
    // All the taxing stuff you do
}, 250);
window.addEventListener('resize', myEfficientFn);

pool

As I mentioned with the debounce function, sometimes you don't get to plug into an event to signify a desired state -- if the event doesn't exist, you need to check for your desired state at intervals:

function poll(fn, callback, errback, timeout, interval) {
    var endTime = Number(new Date()) + (timeout || 2000);
    interval = interval || 100;

    (function p() {
            // If the condition is met, we're done! 
            if(fn()) {
                callback();
            }
            // If the condition isn't met but the timeout hasn't elapsed, go again
            else if (Number(new Date()) < endTime) {
                setTimeout(p, interval);
            }
            // Didn't match and too much time, reject!
            else {
                errback(new Error('timed out for ' + fn + ': ' + arguments));
            }
    })();
}

// Usage:  ensure element is visible
poll(
    function() {
        return document.getElementById('lightbox').offsetWidth > 0;
    },
    function() {
        // Done, success callback
    },
    function() {
        // Error, failure callback
    }
);

once

There are times when you prefer a given functionality to only happen once, similar to the way you'd use an onload event. This code provides you with this functionality:

function once(fn, context) { 
    var result;

    return function() { 
        if(fn) {
            result = fn.apply(context || this, arguments);
            fn = null;
        }

        return result;
    };
}

// Usage
var canOnlyFireOnce = once(function() {
    console.log('Fired!');
});

canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada

..more examples in the link below...

7 Essential JavaScript Functions

Added on 18.Jun.2015
Tags: js functions essential good practice

Mint-X theme padding compact fix

Open gtk-3.0/gtk-widgets.css

and edit line 520

.entry {
    padding: 1px; /* old 4px 5px 4px 5px */
    color: @theme_text_color;
}

line 1909

.toolbar {
    padding: 0; /* old 6px */
    border-style: none;
    background-color: @theme_bg_color;
}

than lines 1922 and 1923

.primary-toolbar .toolbar,
.primary-toolbar.toolbar {
    -GtkWidget-window-dragging: true;
    -GtkToolbar-button-relief: normal;
    padding-top: 0;
    padding-bottom: 1px;
    border-style: solid;
    border-width: 0 0 1px 0;
    border-color: @border;
    color: @theme_fg_color;
    text-shadow: 0 1px @button_text_shadow;
}

Added on 05.Jun.2015
Tags: min linux theme fix padding

Remove specific element from an array in JavaScript

First, find the index of the element you want to remove:

var array = [2, 5, 9];
var index = array.indexOf(5);

Then remove it with splice:

if (index > -1) {
    array.splice(index, 1);
}

You can also use delete array[i];, but it will leave a undefined value in the array.

Here is a good example extending the array object to support a new method called remove!

var arr = ['hello', 'world', 'matrix'];

console.log(arr);
// ["hello", "world", "matrix"]

Array.prototype.remove = function(entry) {
  this.splice(this.indexOf(entry), 1);
  return this;
};

console.log(arr.remove('world'));
// ["hello", "matrix"]

More examples at stackoverflow

Added on 03.Jun.2015
Tags: js array remove delete

Bulk import a file to 'Redis' database

cat file.txt | xargs -L1 redis-cli

stackoverflow

Added on 29.May.2015
Tags: redis import bulk database linux terminal

How to find if an array contains a specific string in JavaScript

var arr = ['create', 'edit', 'enable', 'disable', 'check', 'fire'];

function inArray(needle, arrhaystack) {
    return (arrhaystack.indexOf(needle) > -1);
}

console.log(inArray('edit', arr));
console.log(inArray('restart', arr));

stackoverflow

Added on 29.May.2015
Tags: js string find array

Search


PHP Libraries


Carbon lib / docs
Idiorm lib / docs
Image Workshop lib / docs
lorenzos/Minixed lib / docs
Parsedown lib / docs
PHP Paginator lib / docs
PHP Redis lib / docs
QrCode lib / docs
Requests lib / docs
Slim lib / docs
Spyc lib / docs
TWIG lib / docs
Upload lib / docs
Validation lib / docs
Zebra Image lib / docs

JS Libraries


AJV lib / docs
BackboneJS lib / docs
Bootstrap Notify lib / docs
C3.js lib / docs
ChartJS lib / docs
FastMD5 lib / docs
HighlightJS lib / docs
jQuery-Storage lib / docs
JS-Cookie lib / docs
Leaflet JS lib / docs
LowDB lib / docs
Marked lib / docs
NeedlyJS lib / docs
ParcelJS lib / docs
RequireJS lib / docs
Swig lib / docs
Toastr lib / docs
Underscore lib / docs
ValidateJS lib / docs
top