Javascript: Remove Hyphens - javascript

So I have been working on this function but I can't figure out how to remove the remainder hyphens at the end of the string.
function solution(s) {
var l = s.length,
max = l - (l % 3 ? ((l + 1) % 3 ? 4 : 2) : 0);
var result = "";
for(var i = 0; i < max; i+=3) {
result += s.replace(/[^0-9]/gi, '').slice(i, i + 3) + "-";
}
for(var i = max; i < l; i+=2) {
result += s.replace(/[^0-9]/gi, '').slice(i, i + 2) + "-";
}
return result.slice(0,-1);
}
console.log(solution("0 - 22 1985--324"));
console.log(solution("555372654"));
I know that "result.slice(0,-1)" should've fixed the issue but it just removes one hyphen at the end.

return /.*[^-]/.exec(result)[0]

Related

Nested while loops in javascript

I'm trying to make a grid of stars with a nested while loop.
It does work with a for loop:
for(m = 1; m <= 5; m++) {
for(n = 1;n <= 10; n++) {
document.write("*" + " ");
}
document.write("<br>");
}
but I can't figure out how I can solve it with a while loop:
while(m <= 5) {
while(n <= 10) {
document.write("*" + " ");
n++;
}
document.write("<br>");
m++;
}
Does anyone have any idea?
Thnx
You're missing the initializers. m needs to start and 1, and n needs to restart at 1 every time m is incremented.
var m, n;
m = 1;
while(m <= 5) {
n = 1;
while(n <= 10) {
document.write("*" + " ");
n++;
}
document.write("<br>");
m++;
}
The problem is that you do not reset the n variable, so everytime it is 10 and thus not entering the while loop. You need to do:
var m = 0,
n = 0,
div = document.getElementById('draw');
function writeToDiv(stringToWrite) {
div.innerHTML = div.innerHTML + stringToWrite;
}
while (m <= 5) {
while (n <= 10) {
writeToDiv("*" + " ");
n++;
}
n = 0;
writeToDiv("<br>");
m++;
}
<div id="draw">
</div>

Create Javascript array with Javascript for loop

I have a series of information that I am looking to cut down to size by looping the information. Here is the original code that is working:
$('#M1s1').css({'visibility': M1s1v});
$('#M1s2').css({'visibility': M1s2v});
$('#M1s3').css({'visibility': M1s3v});
$('#M1s4').css({'visibility': M1s4v});
$('#M1s5').css({'visibility': M1s5v});
$('#M1s6').css({'visibility': M1s6v});
$('#M1s7').css({'visibility': M1s7v});
$('#M2s1').css({'visibility': M2s1v});
$('#M2s2').css({'visibility': M2s2v});
$('#M2s3').css({'visibility': M2s3v});
$('#M2s4').css({'visibility': M2s4v});
$('#M2s5').css({'visibility': M2s5v});
$('#M2s6').css({'visibility': M2s6v});
$('#M2s7').css({'visibility': M2s7v});
$('#M3s1').css({'visibility': M3s1v});
$('#M3s2').css({'visibility': M3s2v});
$('#M3s3').css({'visibility': M3s3v});
$('#M3s4').css({'visibility': M3s4v});
$('#M3s5').css({'visibility': M3s5v});
$('#M3s6').css({'visibility': M3s6v});
$('#M3s7').css({'visibility': M3s7v});
$('#M4s1').css({'visibility': M4s1v});
$('#M4s2').css({'visibility': M4s2v});
$('#M4s3').css({'visibility': M4s3v});
$('#M4s4').css({'visibility': M4s4v});
$('#M4s5').css({'visibility': M4s5v});
$('#M4s6').css({'visibility': M4s6v});
$('#M4s7').css({'visibility': M4s7v});
$('#M5s1').css({'visibility': M5s1v});
$('#M5s2').css({'visibility': M5s2v});
$('#M5s3').css({'visibility': M5s3v});
$('#M5s4').css({'visibility': M5s4v});
$('#M5s5').css({'visibility': M5s5v});
$('#M5s6').css({'visibility': M5s6v});
$('#M5s7').css({'visibility': M5s7v});
And here is the for loops that I created to try and cut down the length of code and possibility of typing errors:
// set smc array(#M1s1, #M1s2, #M1s3, etc.)
var smc = [];
for (m = 1; m < 6; m++) {
for (s = 1; s < 8; s++) {
var smc[] = '#M' + m + 's' + s;
}
}
// set smcv array(#M1s1v, #M1s2v, #M1s3v, etc.)
var smcv = [];
for (mv = 1; mv < 6; mv++) {
for (sv = 1; sv < 8; sv++) {
var smcv[] = '#M' + mv + 's' + sv + 'v';
}
}
// loop to set visibility of small circles
for (i = 0; i < 35; i++) {
$(smc[i]).css({'visibility': smcv[i]});
}
I am really new to javascript loops and feel like I may be overlooking something basic or even a syntax error of some kind but can't put a finger on what the problem is. Any direction or assistance would be greatly appreciated!
UPDATE
Here is the final solution to my problem:
//set smc array(#M1s1, #M1s2, #M1s3, etc.)
var smc = [];
for (m = 1; m < 6; m++) {
for (s = 1; s < 8; s++) {
smc.push('#M' + m + 's' + s);
}
}
//set smcv array(#Ms1v, #M1s2v, #M1s3v, etc.)
var smcv = [];
for (mv = 1; mv < 6; mv++) {
for (sv = 1; sv < 8; sv++) {
smcv.push('M' + mv + 's' + sv + 'v');
}
}
//loop to set visibility of small circles
for (i = 0; i < 35; i++) {
$(smc[i]).css({'visibility': window[smcv[i]]});
}
You can't push value to array using var smc[] = 'something'.
Use smc.push( 'something' )
Lets say the M1s1v,M1s2v,.... values are coming from a json variable, something like this:
var x = {
M1s1v : "hidden",
M1s2v : "visibile",
...
}
then you can cut-short the code to something like this:
for (m = 1; m < 6; m++) {
for (s = 1; s < 8; s++) {
$('#M' + m + 's' + s).css({'visiblity':x['M'+m+'s'+s+'v']});
}
}
Hope it helps.
Say you have a two dimensional array, 5 x 7 for M and s holding something that will evaluate to true/false (boolean, 0, 1, empty string...).
var data = [][];
...
for (var M=0; M < data.length; M++) {
for (var s=0; s < data[M].length; M++) {
$('#M' + (M+1) + 's' + (s+1)).css({'visibility': data[M][s] ? 'visible' : 'hidden'});
}
}
You could "optimize" by using hard coded numbers instead of the lengths if you were centian of the dimensions.

Compare strings with 'similar' letters [duplicate]

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 =)

randomly split up substrings

I am trying to split up substring charaters from a string from what i have tryed so far has failed even looping within a loop.
An example result from string "1234567890" the output could look like as follows
12
345
6
7890
.
var randomChar = ""
var str = "123456789";
for (var j = 0; j < str.length; j++) {
randomChar = Math.floor(Math.random() * 3) + 1;
console.log(str.substr(j, randomChar));
}
here you go:
var substrSize;
while (str.length) {
substrSize = Math.floor(Math.random()*3)+1; // at most 4?
if (substrSize >= str.length)
randomChar = str;
else
randomChar = str.substr(0,substrSize);
str = str.substr(randomChar.length);
console.log(randomChar);
}
or alternatively:
var j = 0;
while (j < str.length) {
var n= j+Math.floor(Math.random() * 3) + 1;
if (n> str.length) n= str.length;
console.log(str.substring(j, n));
j = n;
}
or alternatively:
var j = 0;
while (j < str.length) {
var n= Math.floor(Math.random() * 3) + 1;
if (j+n> str.length) n= str.length-j;
console.log(str.substr(j, n));
j += n;
}
The problem with your code is that you always iterate str.length times. After cutting out for example first 3 random characters you should start from 4th, not from 2nd.
And here is an elegant recursive solution, much different from yours:
function randString(s) {
if(s.length > 0) {
var pivot = Math.ceil(Math.random() * 3);
console.info(s.substring(0, pivot));
randString(s.substring(pivot));
}
}
var randomChar = ""
var str = "123456789";
var j = 0;
while (j < str.length) {
randomChar = Math.floor(Math.random() * 3) + 1;
console.log(str.substr(j, randomChar));
j += randomChar;
}

Javascript: getting rid of nested loop

It's been a while since I wrote any Javascript. Is there a more elegant way to do this. Specifically want to get rid of the second loop:
<script>
var number = 0;
for (var i=1; i<11; i++) {
for (var x=1; x<11; x++) {
if (i==1) {
number = x;
} else {
number = Math.pow(i, x);
}
document.write(number + " ");
if (x == 10) {
document.write("<br>");
}
}
}
</script>
I would stick with 2 loops but i would change one if statement and move it after the 2nd loop and avoid document.write and insert it all at once to reduce the number of time you change the DOM
let result = ''
for (let i = 1; i < 11; i++) {
for (let x = 1; x < 11; x++)
result += (i==1 ? x : Math.pow(i, x)) + ' '
result += '<br>'
}
document.body.insertAdjacentHTML('beforeend', result)
Edit If you really don't want the 2nd loop:
let result = ''
// you must swap the condition to check for x instead of i
for (let i = 1, x = 1; x < 11; i++) {
result += (x==1 ? i : Math.pow(x, i)) + ' '
// and reset i and increase x yourself
if (i == 10) {
i = 0
x++
result += '<br>'
}
}
document.body.insertAdjacentHTML('beforeend', result)
Edit2 just for the fun: No for loops.
Just a recursive function :P
function build(i = 1, x = 1, res = '') {
res += (x == 1 ? i : Math.pow(x, i)) + ' '
i == 10 ? (x++, i=1, res += '<br>') : i++
return x == 11 ? res : build(i, x, res)
}
document.body.insertAdjacentHTML('beforeend', build())
In terms of 'elegancy', I'd go for for... in loops or map function. That doesn't solve your nested loop though.
On a side note, nested loops are not necessarily bad. If that's the correct way to implement the specific algorithm, then that's how it is.
Using Math.pow() is un-necessary overhead. Nested loops are not necessarily bad.
var number = 0;
for (var i=1; i<11; i++) {
document.write(i + " ");
number = i;
for (var x=2; x<11; x++) {
number = (i == 1) ? x : number * i;
document.write(number + " ");
}
document.write("<br>");
}
Another way of doing it with 1 loop only, tho not as clean:
var number = 0;
var x = 1;
var calc = 0;
var calcx = 1;
var increment = false;
for (var i=1; i<101; i++) {
increment = false;
calc = i % 10;
if(calc == 0){
calc = 10;
increment = true;
}
if (calcx==1) {
number = calc;
} else {
number = Math.pow(calcx, calc);
console.log(calcx+" "+calc);
}
document.write(number + " ");
if (i % 10 == 0) {
document.write("<br>");
}
if(increment){
calcx++;
}
}
Here's another way with only one loop:
[...Array(100)].map((_,i) => {
document.write(((i>9)?Math.pow(Math.floor((i+10)/10),(i%10)+1):i+1) + ' ' + ((i%10==9)?'<br>':''));
});

Categories

Resources