Paradoxical Javascript Variable Defining - javascript

I am trying to calculate a maths question. It requires the use of variables within variables that loop around.
Here is my JavaScript Code:
var a = m+1;
var b = n+1;
var c = o+1;
var d = p+1;
var e = q+1;
var f = r+1;
var g = s+1;
var h = t+1;
var i = u+1;
var j = v+1;
var l = w+1;
var m = (1+b)/2;
var n = (a+c)/2;
var o = (b+d)/2;
var p = (c+e)/2;
var q = (d+f)/2;
var r = (e+g)/2;
var s = (f+h)/2;
var t = (g+i)/2;
var u = (h+j)/2;
var v = (i+l)/2;
var w = (j+12)/2;
function CalculateA() {
alert(a);
}
The HTML is just a button calling CalculateA() Function.
This results with undefined. Is there a way to properly calculate this or is it not possible with javascript or coding.
Edit
I relize now that this isn't working very well.
Also I ran it through excel with looping calculations and found the answer.
Thanks for all your help anyway.
https://drive.google.com/open?id=0B9I2lCue4HpLZEh3X0NGTUE4YXM
The Excel Calculation ^

You could give all variables a start value of zero to prevent NaN and then call the operations again until a is converging to 12.916666666666651.
function calc() {
a = m + 1;
b = n + 1;
c = o + 1;
d = p + 1;
e = q + 1;
f = r + 1;
g = s + 1;
h = t + 1;
i = u + 1;
j = v + 1;
l = w + 1;
m = (1 + b) / 2;
n = (a + c) / 2;
o = (b + d) / 2;
p = (c + e) / 2;
q = (d + f) / 2;
r = (e + g) / 2;
s = (f + h) / 2;
t = (g + i) / 2;
u = (h + j) / 2;
v = (i + l) / 2;
w = (j + 12) / 2;
console.log(a);
}
var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, i = 0, j = 0, l = 0, m = 0, n = 0, o = 0, p = 0, q = 0, r = 0, s = 0, t = 0, u = 0, v = 0, w = 0,
ii, letter;
for (ii = 0; ii < 1000; ii++) {
calc();
}
for (ii = 1; ii <= 23; ii++) {
letter = (ii + 9).toString(36);
letter === 'k' || console.log(letter, window[letter]); // k is missing ...
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

Nothing is impossible in coding. it is returning undefined because 'a' is declared on top where m is not defined and it is "NaN" error -- Not a Number.

The variables end up depending onto each other, which means that your result will always be NaN.
Javascript tries to give you an exact result for the formula, which it can't. What you need for this math issue, is to replace the variables in each term with each other, to get to a result with only 1 variable - I don't think there's a way for you to do that in Javascript with less effort than doing it manually.

Related

How to convert between Lat Long and MGRS using javascript without dependence on libraries

I have a mapping app running in a browser than needs to be able to convert between latitude longitude and MGRS. I need to keep the load time of the app fast so I do not want to include any libraries with additional functions I do not need.
I solved this by developing the following two functions combining bits from two primary sources plus others on the internet. I have optimised them for speed not understanding!
My two primary sources were:
http://www.movable-type.co.uk/scripts/latlong-utm-mgrs.html
http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html
Example usage : MGRSString (51.172,-1.779) returns
"30U WB 85358 69660"
function MGRSString (Lat, Long)
{
if (Lat < -80) return 'Too far South' ; if (Lat > 84) return 'Too far North' ;
var c = 1 + Math.floor ((Long+180)/6);
var e = c*6 - 183 ;
var k = Lat*Math.PI/180;
var l = Long*Math.PI/180;
var m = e*Math.PI/180;
var n = Math.cos (k);
var o = 0.006739496819936062*Math.pow (n,2);
var p = 40680631590769/(6356752.314*Math.sqrt(1 + o));
var q = Math.tan (k);
var r = q*q;
var s = (r*r*r) - Math.pow (q,6);
var t = l - m;
var u = 1.0 - r + o;
var v = 5.0 - r + 9*o + 4.0*(o*o);
var w = 5.0 - 18.0*r + (r*r) + 14.0*o - 58.0*r*o;
var x = 61.0 - 58.0*r + (r*r) + 270.0*o - 330.0*r*o;
var y = 61.0 - 479.0*r + 179.0*(r*r) - (r*r*r);
var z = 1385.0 - 3111.0*r + 543.0*(r*r) - (r*r*r);
var aa = p*n*t + (p/6.0*Math.pow (n,3)*u*Math.pow (t,3)) + (p/120.0*Math.pow (n,5)*w*Math.pow (t,5)) + (p/5040.0*Math.pow (n,7)*y*Math.pow (t,7));
var ab = 6367449.14570093*(k - (0.00251882794504*Math.sin (2*k)) + (0.00000264354112*Math.sin (4*k)) - (0.00000000345262*Math.sin (6*k)) + (0.000000000004892*Math.sin (8*k))) + (q/2.0*p*Math.pow (n,2)*Math.pow (t,2)) + (q/24.0*p*Math.pow (n,4)*v*Math.pow (t,4)) + (q/720.0*p*Math.pow (n,6)*x*Math.pow (t,6)) + (q/40320.0*p*Math.pow (n,8)*z*Math.pow (t,8));
aa = aa*0.9996 + 500000.0;
ab = ab*0.9996; if (ab < 0.0) ab += 10000000.0;
var ad = 'CDEFGHJKLMNPQRSTUVWXX'.charAt (Math.floor (Lat/8 + 10));
var ae = Math.floor (aa/100000);
var af = ['ABCDEFGH','JKLMNPQR','STUVWXYZ'][(c-1)%3].charAt (ae-1);
var ag = Math.floor (ab/100000)%20;
var ah = ['ABCDEFGHJKLMNPQRSTUV','FGHJKLMNPQRSTUVABCDE'][(c-1)%2].charAt (ag);
function pad (val) {if (val < 10) {val = '0000' + val} else if (val < 100) {val = '000' + val} else if (val < 1000) {val = '00' + val} else if (val < 10000) {val = '0' + val};return val};
aa = Math.floor (aa%100000); aa = pad (aa);
ab = Math.floor (ab%100000); ab = pad (ab);
return c + ad + ' ' + af + ah + ' ' + aa + ' ' + ab;
};
To convert back from mgrs to lat long use the following function. The input string must have metre (i.e. 5 digit) easing and northing resolution and have spaces as output by the above function.
function LatLongFromMGRSstring (a)
{
var b = a.trim();
b = b.match(/\S+/g);
if (b == null || b.length != 4) return [false,null,null];
var c = (b[0].length < 3) ? b[0][0] : b[0].slice(0,2);
var d = (b[0].length < 3) ? b[0][1] : b[0][2];
var e = (c*6-183)*Math.PI / 180;
var f = ["ABCDEFGH","JKLMNPQR","STUVWXYZ"][(c-1) % 3].indexOf(b[1][0]) + 1;
var g = "CDEFGHJKLMNPQRSTUVWXX".indexOf(d);
var h = ["ABCDEFGHJKLMNPQRSTUV","FGHJKLMNPQRSTUVABCDE"][(c-1) % 2].indexOf(b[1][1]);
var i = [1.1,2.0,2.8,3.7,4.6,5.5,6.4,7.3,8.2,9.1,0,0.8,1.7,2.6,3.5,4.4,5.3,6.2,7.0,7.9];
var j = [0,2,2,2,4,4,6,6,8,8,0,0,0,2,2,4,4,6,6,6];
var k = i[g];
var l = Number(j[g]) + h / 10;
if (l < k) l += 2;
var m = f*100000.0 + Number(b[2]);
var n = l*1000000 + Number(b[3]);
m -= 500000.0;
if (d < 'N') n -= 10000000.0;
m /= 0.9996; n /= 0.9996;
var o = n / 6367449.14570093;
var p = o + (0.0025188266133249035*Math.sin(2.0*o)) + (0.0000037009491206268*Math.sin(4.0*o)) + (0.0000000074477705265*Math.sin(6.0*o)) + (0.0000000000170359940*Math.sin(8.0*o));
var q = Math.tan(p);
var r = q*q;
var s = r*r;
var t = Math.cos(p);
var u = 0.006739496819936062*Math.pow(t,2);
var v = 40680631590769 / (6356752.314*Math.sqrt(1 + u));
var w = v;
var x = 1.0 / (w*t); w *= v;
var y = q / (2.0*w); w *= v;
var z = 1.0 / (6.0*w*t); w *= v;
var aa = q / (24.0*w); w *= v;
var ab = 1.0 / (120.0*w*t); w *= v;
var ac = q / (720.0*w); w *= v;
var ad = 1.0 / (5040.0*w*t); w *= v;
var ae = q / (40320.0*w);
var af = -1.0-u;
var ag = -1.0-2*r-u;
var ah = 5.0 + 3.0*r + 6.0*u-6.0*r*u-3.0*(u*u)-9.0*r*(u*u);
var ai = 5.0 + 28.0*r + 24.0*s + 6.0*u + 8.0*r*u;
var aj = -61.0-90.0*r-45.0*s-107.0*u + 162.0*r*u;
var ak = -61.0-662.0*r-1320.0*s-720.0*(s*r);
var al = 1385.0 + 3633.0*r + 4095.0*s + 1575*(s*r);
var lat = p + y*af*(m*m) + aa*ah*Math.pow(m,4) + ac*aj*Math.pow(m,6) + ae*al*Math.pow(m,8);
var lng = e + x*m + z*ag*Math.pow(m,3) + ab*ai*Math.pow(m,5) + ad*ak*Math.pow(m,7);
lat = lat*180 / Math.PI;
lng = lng*180 / Math.PI;
return [true,lat,lng];
}

I don't understand this Javascript?

Can someone walk me thru this example and why it prints 10? I see to be getting confused on the function in function aspect I think. Also what is the difference between var x = and x = ?
var x = 6;
var y = 4;
var a = function(b) {
return function(c) {
return y + b + c;
}
};
x = 2;
y = 5;
var fn = a(x);
x = 1;
y = 3;
var unknown = 5;
console.log(fn(unknown));
var x = 6;
var y = 4;
var a = function(b) {
return function(c) {
return y + b + c;
}
};
x = 2;
y = 5; // unnecessary, meant to confuse
var fn = a(x); // creates a closure, where b equals 2
x = 1; // unnecessary, meant to confuse
y = 3;
var unknown = 5;
console.log(fn(unknown)); // y=3,b=2,c=5, total = 10

Using javascript vars as array key names

I'm making a grid of 18 x 9 and want to calculate the sizes for all possible boxes that could be placed on the grid.
I'm placing them in objects, but the line
var template_sizes_site[x + 'x' + y] = {};
Is failing. it seems I can't use variables AND a string to name key?
I want basically to say array['2x9']['width'] = 42; etc
What am I missing?
var template_sizes = {};
var site_width = 70;
var site_height = 70;
var site_margin = 20;
for (var y = 1; y <= 9; y++)
{
for (var x = 1; x <= 18; x++)
{
var template_sizes_site[x + 'x' + y] = {};
template_sizes_site[x + 'x' + y]['width'] = ((site_width * x) + (x > 1 ? site_margin * (x - 1) : 0));
template_sizes_site[x + 'x' + y]['height'] = ((site_height * y) + (y > 1 ? site_margin * (y - 1) : 0));
}
}
Remove the var from your first line in the body of your nested for loop:
var template_sizes = {};
var site_width = 70;
var site_height = 70;
var site_margin = 20;
for (var y = 1; y <= 9; y++)
{
for (var x = 1; x <= 18; x++)
{
template_sizes_site[x + 'x' + y] = {};
template_sizes_site[x + 'x' + y]['width'] = ((site_width * x) + (x > 1 ? site_margin * (x - 1) : 0));
template_sizes_site[x + 'x' + y]['height'] = ((site_height * y) + (y > 1 ? site_margin * (y - 1) : 0));
}
}
var is only for variables, not for properties:
var template = {}; // OK
var template_sizes_site[x + 'x' + y] = {}; // not allowed, no need
Also you'll need to initialise template_sizes_site if that wasn't a typo.
You did not initialize your variable template_sizes_site (is this meant to be template_sizes ?). Also you could shorten your initialization code a little like shown below.
var template_sizes = {},
template_sizes_site = {},
site_width = 70,
site_height = 70,
site_margin = 20;
for (var y = 1; y <= 9; y++) {
for (var x = 1; x <= 18; x++) {
template_sizes_site[x + 'x' + y] = {
'width': ((site_width * x) + (x > 1 ? site_margin * (x - 1) : 0)),
'height': ((site_height * y) + (y > 1 ? site_margin * (y - 1) : 0))
};
}
}
You need to change var template_sizes_site[x + 'x' + y] = {}; into template_sizes_site[x + 'x' + y] = {}; because your way creates local variable in scope and after leaving it (when loop goes to next time) data is becomes lost.
Also template_sizes_site is not initialized if it is all your code.

Shell Sort don't working on JavaScript

I have an code in Java and it works perfect, but the code translated to JavaScript throw an error. The ShellSort method pass a Array to the method.(I am using the console to debug) My code is:
this.shellSort = function(nums)
{
//O contador de tempo inicia aqui
var tempoSS = new Date();
var n = nums.length;
console.log("n = ",n);
var h = n / 2;
console.log("h = ",h);
var c, j;
while (h > 0)
{
for (var i = h; i < n; i++)
{
c = nums[i];
j = i;
while (j >= h && nums[j - h] > c)
{
nums[j] = nums[j - h];
console.log("nums["+j+"] = ",nums[j]);
j = j - h;
console.log("j = ",j);
}
nums[j] = c;
console.log("nums["+j+"] = ",nums[j]);
}
h = h / 2;
console.log("h = ",h);
}
the error is caught is --
[13:52:59.581] ReferenceError: reference to undefined property nums[(j - h)] # file:///C:/Documents%20and%20Settings/erickribeiro/Desktop/www/index.html:240
Test page: dev.erickribeiro.com.br/index.html
The full script is the html page.
What is wrong?
I believe you're getting stuck in an endless loop because h may be a float sometimes. You have to ensure it's an integer (which in Java it is always, since you probably declared it as such):
this.shellSort = function(nums)
{
//O contador de tempo inicia aqui
var tempoSS = new Date();
var n = nums.length;
console.log("n = ",n);
// HERE:
var h = Math.floor(n / 2);
console.log("h = ",h);
var c, j;
while (h > 0)
{
for (var i = h; i < n; i++)
{
c = nums[i];
j = i;
while (j >= h && nums[j - h] > c)
{
nums[j] = nums[j - h];
console.log("nums["+j+"] = ",nums[j]);
j = j - h;
console.log("j = ",j);
}
nums[j] = c;
console.log("nums["+j+"] = ",nums[j]);
}
// AND HERE:
h = Math.floor(h / 2);
console.log("h = ",h);
}
}

Sort an array by the "Levenshtein Distance" with best performance in Javascript

So I have a random javascript array of names...
[#larry,#nicholas,#notch] etc.
They all start with the # symbol. I'd like to sort them by the Levenshtein Distance so that the the ones at the top of the list are closest to the search term. At the moment, I have some javascript that uses jQuery's .grep() on it using javascript .match() method around the entered search term on key press:
(code edited since first publish)
limitArr = $.grep(imTheCallback, function(n){
return n.match(searchy.toLowerCase())
});
modArr = limitArr.sort(levenshtein(searchy.toLowerCase(), 50))
if (modArr[0].substr(0, 1) == '#') {
if (atRes.childred('div').length < 6) {
modArr.forEach(function(i){
atRes.append('<div class="oneResult">' + i + '</div>');
});
}
} else if (modArr[0].substr(0, 1) == '#') {
if (tagRes.children('div').length < 6) {
modArr.forEach(function(i){
tagRes.append('<div class="oneResult">' + i + '</div>');
});
}
}
$('.oneResult:first-child').addClass('active');
$('.oneResult').click(function(){
window.location.href = 'http://hashtag.ly/' + $(this).html();
});
It also has some if statements detecting if the array contains hashtags (#) or mentions (#). Ignore that. The imTheCallback is the array of names, either hashtags or mentions, then modArr is the array sorted. Then the .atResults and .tagResults elements are the elements that it appends each time in the array to, this forms a list of names based on the entered search terms.
I also have the Levenshtein Distance algorithm:
var levenshtein = function(min, split) {
// Levenshtein Algorithm Revisited - WebReflection
try {
split = !("0")[0]
} catch(i) {
split = true
};
return function(a, b) {
if (a == b)
return 0;
if (!a.length || !b.length)
return b.length || a.length;
if (split) {
a = a.split("");
b = b.split("")
};
var len1 = a.length + 1,
len2 = b.length + 1,
I = 0,
i = 0,
d = [[0]],
c, j, J;
while (++i < len2)
d[0][i] = i;
i = 0;
while (++i < len1) {
J = j = 0;
c = a[I];
d[i] = [i];
while(++j < len2) {
d[i][j] = min(d[I][j] + 1, d[i][J] + 1, d[I][J] + (c != b[J]));
++J;
};
++I;
};
return d[len1 - 1][len2 - 1];
}
}(Math.min, false);
How can I work with algorithm (or a similar one) into my current code to sort it without bad performance?
UPDATE:
So I'm now using James Westgate's Lev Dist function. Works WAYYYY fast. So performance is solved, the issue now is using it with source...
modArr = limitArr.sort(function(a, b){
levDist(a, searchy)
levDist(b, searchy)
});
My problem now is general understanding on using the .sort() method. Help is appreciated, thanks.
Thanks!
I wrote an inline spell checker a few years ago and implemented a Levenshtein algorithm - since it was inline and for IE8 I did quite a lot of performance optimisation.
var levDist = function(s, t) {
var d = []; //2d matrix
// Step 1
var n = s.length;
var m = t.length;
if (n == 0) return m;
if (m == 0) return n;
//Create an array of arrays in javascript (a descending loop is quicker)
for (var i = n; i >= 0; i--) d[i] = [];
// Step 2
for (var i = n; i >= 0; i--) d[i][0] = i;
for (var j = m; j >= 0; j--) d[0][j] = j;
// Step 3
for (var i = 1; i <= n; i++) {
var s_i = s.charAt(i - 1);
// Step 4
for (var j = 1; j <= m; j++) {
//Check the jagged ld total so far
if (i == j && d[i][j] > 4) return n;
var t_j = t.charAt(j - 1);
var cost = (s_i == t_j) ? 0 : 1; // Step 5
//Calculate the minimum
var mi = d[i - 1][j] + 1;
var b = d[i][j - 1] + 1;
var c = d[i - 1][j - 1] + cost;
if (b < mi) mi = b;
if (c < mi) mi = c;
d[i][j] = mi; // Step 6
//Damerau transposition
if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
// Step 7
return d[n][m];
}
I came to this solution:
var levenshtein = (function() {
var row2 = [];
return function(s1, s2) {
if (s1 === s2) {
return 0;
} else {
var s1_len = s1.length, s2_len = s2.length;
if (s1_len && s2_len) {
var i1 = 0, i2 = 0, a, b, c, c2, row = row2;
while (i1 < s1_len)
row[i1] = ++i1;
while (i2 < s2_len) {
c2 = s2.charCodeAt(i2);
a = i2;
++i2;
b = i2;
for (i1 = 0; i1 < s1_len; ++i1) {
c = a + (s1.charCodeAt(i1) === c2 ? 0 : 1);
a = row[i1];
b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
row[i1] = b;
}
}
return b;
} else {
return s1_len + s2_len;
}
}
};
})();
See also http://jsperf.com/levenshtein-distance/12
Most speed was gained by eliminating some array usages.
Updated: http://jsperf.com/levenshtein-distance/5
The new Revision annihilates all other benchmarks. I was specifically chasing Chromium/Firefox performance as I don't have an IE8/9/10 test environment, but the optimisations made should apply in general to most browsers.
Levenshtein Distance
The matrix to perform Levenshtein Distance can be reused again and again. This was an obvious target for optimisation (but be careful, this now imposes a limit on string length (unless you were to resize the matrix dynamically)).
The only option for optimisation not pursued in jsPerf Revision 5 is memoisation. Depending on your use of Levenshtein Distance, this could help drastically but was omitted due to its implementation specific nature.
// Cache the matrix. Note this implementation is limited to
// strings of 64 char or less. This could be altered to update
// dynamically, or a larger value could be used.
var matrix = [];
for (var i = 0; i < 64; i++) {
matrix[i] = [i];
matrix[i].length = 64;
}
for (var i = 0; i < 64; i++) {
matrix[0][i] = i;
}
// Functional implementation of Levenshtein Distance.
String.levenshteinDistance = function(__this, that, limit) {
var thisLength = __this.length, thatLength = that.length;
if (Math.abs(thisLength - thatLength) > (limit || 32)) return limit || 32;
if (thisLength === 0) return thatLength;
if (thatLength === 0) return thisLength;
// Calculate matrix.
var this_i, that_j, cost, min, t;
for (i = 1; i <= thisLength; ++i) {
this_i = __this[i-1];
for (j = 1; j <= thatLength; ++j) {
// Check the jagged ld total so far
if (i === j && matrix[i][j] > 4) return thisLength;
that_j = that[j-1];
cost = (this_i === that_j) ? 0 : 1; // Chars already match, no ++op to count.
// Calculate the minimum (much faster than Math.min(...)).
min = matrix[i - 1][j ] + 1; // Deletion.
if ((t = matrix[i ][j - 1] + 1 ) < min) min = t; // Insertion.
if ((t = matrix[i - 1][j - 1] + cost) < min) min = t; // Substitution.
matrix[i][j] = min; // Update matrix.
}
}
return matrix[thisLength][thatLength];
};
Damerau-Levenshtein Distance
jsperf.com/damerau-levenshtein-distance
Damerau-Levenshtein Distance is a small modification to Levenshtein Distance to include transpositions. There is very little to optimise.
// Damerau transposition.
if (i > 1 && j > 1 && this_i === that[j-2] && this[i-2] === that_j
&& (t = matrix[i-2][j-2]+cost) < matrix[i][j]) matrix[i][j] = t;
Sorting Algorithm
The second part of this answer is to choose an appropriate sort function. I will upload optimised sort functions to http://jsperf.com/sort soon.
I implemented a very performant implementation of levenshtein distance calculation if you still need this.
function levenshtein(s, t) {
if (s === t) {
return 0;
}
var n = s.length, m = t.length;
if (n === 0 || m === 0) {
return n + m;
}
var x = 0, y, a, b, c, d, g, h, k;
var p = new Array(n);
for (y = 0; y < n;) {
p[y] = ++y;
}
for (; (x + 3) < m; x += 4) {
var e1 = t.charCodeAt(x);
var e2 = t.charCodeAt(x + 1);
var e3 = t.charCodeAt(x + 2);
var e4 = t.charCodeAt(x + 3);
c = x;
b = x + 1;
d = x + 2;
g = x + 3;
h = x + 4;
for (y = 0; y < n; y++) {
k = s.charCodeAt(y);
a = p[y];
if (a < c || b < c) {
c = (a > b ? b + 1 : a + 1);
}
else {
if (e1 !== k) {
c++;
}
}
if (c < b || d < b) {
b = (c > d ? d + 1 : c + 1);
}
else {
if (e2 !== k) {
b++;
}
}
if (b < d || g < d) {
d = (b > g ? g + 1 : b + 1);
}
else {
if (e3 !== k) {
d++;
}
}
if (d < g || h < g) {
g = (d > h ? h + 1 : d + 1);
}
else {
if (e4 !== k) {
g++;
}
}
p[y] = h = g;
g = d;
d = b;
b = c;
c = a;
}
}
for (; x < m;) {
var e = t.charCodeAt(x);
c = x;
d = ++x;
for (y = 0; y < n; y++) {
a = p[y];
if (a < c || d < c) {
d = (a > d ? d + 1 : a + 1);
}
else {
if (e !== s.charCodeAt(y)) {
d = c + 1;
}
else {
d = c;
}
}
p[y] = d;
c = a;
}
h = d;
}
return h;
}
It was my answer to a similar SO question
Fastest general purpose Levenshtein Javascript implementation
Update
A improved version of the above is now on github/npm see
https://github.com/gustf/js-levenshtein
The obvious way of doing this is to map each string to a (distance, string) pair, then sort this list, then drop the distances again. This way you ensure the levenstein distance only has to be computed once. Maybe merge duplicates first, too.
I would definitely suggest using a better Levenshtein method like the one in #James Westgate's answer.
That said, DOM manipulations are often a great expense. You can certainly improve your jQuery usage.
Your loops are rather small in the example above, but concatenating the generated html for each oneResult into a single string and doing one append at the end of the loop will be much more efficient.
Your selectors are slow. $('.oneResult') will search all elements in the DOM and test their className in older IE browsers. You may want to consider something like atRes.find('.oneResult') to scope the search.
In the case of adding the click handlers, we may want to do one better avoid setting handlers on every keyup. You could leverage event delegation by setting a single handler on atRest for all results in the same block you are setting the keyup handler:
atRest.on('click', '.oneResult', function(){
window.location.href = 'http://hashtag.ly/' + $(this).html();
});
See http://api.jquery.com/on/ for more info.
I just wrote an new revision: http://jsperf.com/levenshtein-algorithms/16
function levenshtein(a, b) {
if (a === b) return 0;
var aLen = a.length;
var bLen = b.length;
if (0 === aLen) return bLen;
if (0 === bLen) return aLen;
var len = aLen + 1;
var v0 = new Array(len);
var v1 = new Array(len);
var i = 0;
var j = 0;
var c2, min, tmp;
while (i < len) v0[i] = i++;
while (j < bLen) {
c2 = b.charAt(j++);
v1[0] = j;
i = 0;
while (i < aLen) {
min = v0[i] - (a.charAt(i) === c2 ? 1 : 0);
if (v1[i] < min) min = v1[i];
if (v0[++i] < min) min = v0[i];
v1[i] = min + 1;
}
tmp = v0;
v0 = v1;
v1 = tmp;
}
return v0[aLen];
}
This revision is faster than the other ones. Works even on IE =)

Categories