[JS] Fastest way for searching a monodimensional array?
var myAr = ['apple', 5, 6];
if(String('^' + myAr.join('^')).indexOf("^5") != -1)
console.log("found!");
else
console.log("not found :(");
About
Hi, I'm Christian Castelli, a 28 years old italian programmer located in Pisa (Italy). Here I post small snippets of code which can be useful in my work.Links
Codepuzzling main siteMy Life Style
while(passion) {
try {
myLife.run();
}catch(LifeExceptions) {
stronger++;
continue;
}
}
Following
var myAr = ['apple', 5, 6];
if(String('^' + myAr.join('^')).indexOf("^5") != -1)
console.log("found!");
else
console.log("not found :(");
I’ve taken this little piece of code around the Web (sorry, I forgot the original source) and it’s a good example on how to develop a plugin for jQuery:
/** Usage:
* $.random(int);
* $.randomBetween(min, max); */
jQuery.extend({
random: function(X) {
return Math.floor(X * (Math.random() % 1));
},
randomBetween: function(MinV, MaxV) {
return MinV + jQuery.random(MaxV - MinV + 1);
}
});
Regular expressions are a very powerful weapon for the developer if he can deals with all the pain of testing, debugging and learning the quirks of this matter. I’m collecting some links to be red one day, when I’ll got time to dive more deeply in the argument:
java.util.regex. If you’re looking for regex testing targeting java, take a look at Regular Expression Test Applet;Self explanatory code:
var T = {
getUnixTime: function() {
return parseInt(new Date().getTime().toString().substring(0, 10));
},
// format hh:mm:ss
getTime: function()
{
var d= new Date();
var time = new Array();
var hours = d.getHours();
time.push(hours);
var minutes = d.getMinutes().toString().length < 2 ? "0"+d.getMinutes() : d.getMinutes();
time.push(minutes);
var seconds = d.getSeconds().toString().length < 2 ? "0"+d.getSeconds() : d.getSeconds();
time.push(seconds);
return time.join(":");
}
}
Update: I’ve just discovered that Syntax Highlighter code doesn’t work well with < > symbols in javascript code….
The code is self explanatory: you have an array and you want to know what index has the element “pippo” or “5”. So I extended the array object with prototype keyword to scan the array and to return the index if found, -1 otherwise.
var points = [56,12,36];
Array.prototype.getIndex = function(aVal)
{
for(item in this)
if(aVal == this[item])
return item;
return -1;
}
console.log(points.getIndex(36));
If you have Firefox or Safari (maybe in IE8 too, I dunno), watch at the console and you’ll see2 as result.
Since many libraries make use of the $ identifier, we need a way to prevent collisions between these names. jQuery provides a method called .noConflict() to return control of the $ identifier back to other libraries. Typical usage of .noConflict() follows the following pattern:
First, the other library (Prototype in this example) is included. Then, jQuery itself is included, taking over $ for its own use. Next, a call to
.noConflict() frees up $, so that control of it reverts to the first included library (Prototype). Now in our custom script we can use both libraries—but whenever we need to use a jQuery method, we need to use jQuery instead of $ as an identifier.
// apply a class to all <a> which respect the filter selection.
$('a').filter(function() {
return this.hostname && this.hostname != location.hostname;
}).addClass('external');
I’ve found always useful using Bin-Blog’s dump function to explore the properties of an object or an array (like a PHP print_r) but now I’ve discovered that console.dir function does the same:
a = ['a', 1, true]; console.dir(a);console.dir function will produce in output console this result:
>>> a = ['a', 1, true]; console.dir(a) 0 "a" 1 1 2 true
// returns 1 if defined, 0 otherwise.
function isDefined(anObj) {
switch(typeof(anObj)) {
case "string": if(anObj != "") return 1; else return 0;
case "undefined": return 0;
case "object": if(anObj != null) return 1; else return 0;
default: return 0;
}
}
Simple class to trim,ltrim and rtrim as it’s common in other languages.
trim = { both : function(str,ch) { # Equivalent to trim return trim.lead(trim.trail(str,ch),ch); }, lead : function(str,ch) { # Equivalent to ltrim if (!ch) ch="\\s" return str.replace( new RegExp("^["+ch+"]+", "g"), "" ); }, trail : function(str,ch) { # Equivalent to rtrim if (!ch) ch="\\s"; return str.replace( new RegExp("["+ch+"]+$", "g"), "" ); } }You can use it like this
s = " string "; # Trim both left and right, every type of char alert(trim.both(s)); # Trim only right, and just look for \n alert(trim.trail(s,"\\n"));