7 JavaScript Functions for every developer to know
You can count the early days of JavaScript where, single function was needed for just about everything because the browser vendors used to practice features in a different way & we are talking about the edge features, not just the basic ones, with addEventListener and attachEvent to name a few .
We know that bygone days have gone when things used to be difficult but still there are a few functions being the same & are must for each developer to keep in their arsenal for an effortless, well –performing task & that’s what they need:
debounce
The debounce function can make the entire game reverse especially, when you need an event-fueled performance. If you aren't using this function with a scroll, resize, key* event, you're most likely doing it incorrectly. Here's how debounce function actually works to keep your code competent:
// 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);
Interestingly, the debounce function will not permit a callback to be used more than one time within given time frame. This is particularly most important while communicating a callback function key to frequently-firing actions.
The debounce function, as mentioned earlier doesn’t support the plug into an event to indicate a desired state -- if the event is missing, it’s time for you need to run check for your desired state at intervals:
// The polling function
function poll(fn, timeout, interval) {
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
var checkCondition = function(resolve, reject) {
// If the condition is met, we're done!
var result = fn();
if(result) {
resolve(result);
}
// If the condition isn't met but the timeout hasn't elapsed, go again
else if (Number(new Date()) < endTime) {
setTimeout(checkCondition, interval, resolve, reject);
}
// Didn't match and too much time, reject!
else {
reject(new Error('timed out for ' + fn + ': ' + arguments));
}
};
return new Promise(checkCondition);
}
// Usage: ensure element is visible
poll(function() {
return document.getElementById('lightbox').offsetWidth > 0;
}, 2000, 150).then(function() {
// Polling done, now do something else!
}).catch(function() {
// Polling timed out, handle the error!
});
Polling has way long been practical on the web and will continue to be the future!
Sometimes you prefer to work with a certain functionality only once, similarly the way you'd use an onload event. This code offers you with the said functionality aspect:
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
The once function prevents replica initialization & make sure that the function appears only for one time.
Getting an absolute URL out of a variable string isn’t an easy to get task.
You can get string input with the get absolute URL easily – a suave trick:
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
};
})();
// Usage
getAbsoluteUrl('/something'); // https://davidwalsh.name/something
The "burn" element href guarantees you with a trustable absolute URL in return.
To know whether a given function is native or can’t signal if you're eager to override is the key query. This clever code can give you the right answer:
;(function() {
// Used to resolve the internal `Class` of values
var toString = Object.prototype.toString;
// Used to resolve the decompiled source of functions
var fnToString = Function.prototype.toString;
// Used to detect host constructors (Safari > 4; really typed array specific)
var reHostCtor = /^\[object .+?Constructor\]$/;
// Compile a regexp using a common native method as a template.
// We chose 'Object#toString` because there's a good chance it is not being mucked with.
var reNative = RegExp('^' +
// Coerce `Object#toString` to a string
String(toString)
// Escape any special regexp characters
.replace(/[.*+?^${}()|[\]\/\\]/g, '\\$&')
// Replace mentions of `toString` with `.*?` to keep the template generic.
// Replace thing like `for ...` to support environments like Rhino which add extra info
// such as method arity.
.replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
function isNative(value) {
var type = typeof value;
return type == 'function'
// Use `Function#toString` to bypass the value's own `toString` method
// and avoid being faked out.
? reNative.test(fnToString.call(value))
// Fallback to a host object check because some environments will represent
// things like typed arrays as DOM methods which may not conform to the
// normal native pattern.
: (value && type == 'object' && reHostCtor.test(toString.call(value))) || false;
}
// export however you want
module.exports = isNative;
}());
// Usage
isNative(alert); // true
isNative(myCustomFunction); // false
The function isn't simple tough but gets the work done!
We all are aware that NodeList can be obtained via a selector (through document.querySelectorAll) and offer each of them with a unique style, but what's more resourceful is setting that style as per selector needs (as you do in a style sheet):
var sheet = (function() {
// Create the <style> tag
var style = document.createElement('style');
// Add a media (and/or media query) here if you'd like!
// style.setAttribute('media', 'screen')
// style.setAttribute('media', 'only screen and (max-width : 1024px)')
// WebKit hack :(
style.appendChild(document.createTextNode(''));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
// Usage
sheet.insertRule("header { float: left; opacity: 0.8; }", 1);
This is ideal while working on a dynamic, AJAX-loaded site. If you set the style as per selector, you feel yourself get rid out of styling every element that may go with that selector (at present or in the future).
Oftentimes, what happens is that we validate input prior to moving forward; make sure of a truthy value, ensuring forms data is legal, etc. But how often can we be sure of a certain element for moving forward? You use matchesSelector function in this case to validate if an element is of a given selector -match:
function matchesSelector(el, selector) {
var p = Element.prototype;
var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function(s) {
return [].indexOf.call(document.querySelectorAll(s), this) !== -1;
};
return f.call(el, selector);
}
// Usage
matchesSelector(document.getElementById('myDiv'), 'div.someSelector[some-attribute=true]')
All in all, these seven JavaScript functions must be on fingers of
Have we Web Development Agency Australia missed out any function?
Web Development Agency Australia is a Web Design Company enjoying an edge with awesome web developers under one roof. Shake hands with us today.