how to return '' when called one letter?
function isPalindrome(s) {
var rev = s.split("").reverse().join("");
return s == rev;
}
function longestP(string) {
var maxP = ''; var maxL = 0;
var i = 0;
while(i < string.length) {
length = 1;
while(i+length <= string.length) {
substring = string.slice(i,length);
if(isPalindrome(substring)) {
if(substring.length > maxL) {
maxL = substring.length;
maxP = substring
}
}
length = length +1
}
i++
}
return maxP
}
console.log(longestP('abba'))
console.log(longestP('a'))
Related
This is Fibonacci Generator function that i have created but for some reason i can't seem to get the output for 1 = [0,1] . While it works alright for other conditions.If somebody can point me at what i am doing wrong here.
function bl(n) {
var output = [];
var firstNo = 0;
var secondNo = 1;
if (n === 0) {
output.push(0);
}
if (n === 1) {
output.push(0);
output.push(1);
} else {
for (var i = 0; i < n; i++) {
var sum = firstNo + secondNo;
firstNo = secondNo;
secondNo = sum;
output.push(sum);
}
return output;
}
}
console.log(bl(1));
return output had to be executed for all conditions so just execute it at end of your function.
function bl(n) {
var output = [];
var firstNo = 0;
var secondNo = 1;
if (n === 0) {
output.push(0);
}
if (n === 1) {
output.push(0);
output.push(1);
} else {
for (var i = 0; i < n; i++) {
var sum = firstNo + secondNo;
firstNo = secondNo;
secondNo = sum;
output.push(sum);
}
}
return output;
}
console.log(bl(1));
I get my password spec from an API which then I split the object into the needed fields and check that I have the required number of lower, upper, special and length of my password.
function isStrong(passwordChecker) {
if (!passwordChecker) {
return false;
}
debugger;
var securityOption = JSON.parse(localStorage.getItem("Security"));
var MinLength = securityOption.PasswordMinRequiredLength;
var SpecialChars = securityOption.PasswordMinRequiredNonalphanumericCharacters;
var MinLowercase = securityOption.PasswordMinRequiredLowercase;
var MinUppercase = securityOption.PasswordMinRequiredUppercase;
//LenghtCheck
if (passwordChecker.length < MinLength);
return false;
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
if (MinLowercase > 0) {
if (!CountLowerCase(passwordChecker) > MinLowercase) {
return false;
}
}
if (MinUppercase > 0) {
if (!CountUpperCase(passwordChecker) > MinLowercase) {
return false;
}
}
}
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
function MinLowercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 97 && text[i] <= 122) {
Count++;
}
}
}
function MinUppercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 65 && text[i] <= 90) {
Count++;
}
}
}
Now what I want to do is, check the different conditions as a whole and if all of the conditions are true then change the class to green..
$(pageId + ' #password').bind('keyup', function () {
var currentpassword = $(pageId + ' #password').val();
if (isStrong(currentpassword)) {
$(pageId + ' #password').addClass('green');
} else {
$(pageId + ' #password').addClass('red');
}
});
I am not sure how to check the conditions as a whole and return an overall true because as I start trying in my password it instantly changes to green as in my password spec you do not need any UpperCase or LowerCase letters so on any input of a char it returns true..
You should refactor your functions so that they accept both the string and the parameter and return true or false. For example:
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
Should instead be:
function CountSpecialChars(text, min) {
var count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
count++;
}
}
return count > min;
}
return CountSpecialChars(passwordChecker, SpecialChars);
Also, as a bonus, you could also avoid that for loop for those functions by using replace, like so:
function MinChars(text, min) {
return text.length > min;
}
function MinUppercase(text, min) {
var non_uppers = /[^A-Z]/g;
var uppers = text.replace(non_uppers, text);
return uppers.length > min;
}
function MinLowercase(text, min) {
var non_lowers = /[^a-z]/g;
var lowers = text.replace(non_lowers, text);
return lowers.length > min;
}
function MinSpecialChars(text, min) {
var non_specials = /[^!-\?]/g;
var specials = text.replace(non_specials, text);
return specials.length > min;
}
Now with those functions, you can have:
if !MinChars(pw, MinLength) return false;
if !MinSpecialChars(pw, SpecialChars) return false;
if !MinLowercase(pw, MinLowercase) return false;
if !MinUppercase(pw, MinUppercase) return false;
return true;
I am writing a function that will return an array with prime numbers.
The function should return an array with n elements. (n is a parameter) But it returns only one element. Why?
My codes:
function findPrimes(n)
{
var arr = [];
var currIndex = 0;
var sqrtNum;
var ceiledNum;
var ceiledIndex = 0;
var currCompose;
var res;
for (initNum = 2; arr.length < n; ++initNum)
{
sqrtNum = Math.sqrt(initNum);
ceiledNum = Math.ceil(sqrtNum);
for (currCompose = 2; currCompose <= ceiledNum; ++currCompose)
{
res = initNum % currCompose;
if (res == 0 && initNum != currCompose)
{
break;
}
else if (res == 0 && initNum == currCompose)
{
arr[currIndex] = initNum;
++currIndex;
break;
}
else if (res != 0 && initNum != currCompose)
{
continue;
}
else
{
console.log("Impossible result!");
}
}
}
return arr;
}
findPrimes(2); //return 2
findPrimes(10); //return 2 too
Jsbin
You should not be comparing initNum to currCompose. Keep in mind that initNum is the number you are checking (say, 71), and currCompose will be at most ceil(sqrt(initNum)) (say 9), so the two will never be equal.
Also note that it is best to append to the list and verify that no divisors where found only after the inner loop has finished.
This modified version works.
function findPrimes(n)
{
var arr = [];
var currIndex = 0;
var sqrtNum;
var ceiledNum;
var ceiledIndex = 0;
var currCompose;
var res;
var initNum;
for (initNum = 2; arr.length < n; ++initNum)
{
sqrtNum = Math.sqrt(initNum);
ceiledNum = Math.ceil(sqrtNum);
for (currCompose = 2; currCompose <= ceiledNum; ++currCompose)
{
res = initNum % currCompose;
if (res == 0 && initNum != currCompose)
{
break;
}
}
if (currCompose == ceiledNum+1)
{
arr[currIndex] = initNum;
++currIndex;
}
}
return arr;
}
var primes = findPrimes(6);
document.write(primes);
correct Line 14 of your code as follows and it works like charm.
for (currCompose = 2; currCompose <= initNum; ++currCompose)
function FindPrime(numbers){
if(numbers.constructor === Array){
output = [];
for (var i = numbers.length - 1; i >= 0; i--) {
if(isPrime(numbers[i]) == true){
output.push(numbers[i]);
};
};
return output;
}
}
function isPrime(numb){
if (numb % 2 == 0) return false;
for (var i=3; i<= Math.sqrt(numb); i = i + 2) {
if (numb % i == 0) {
return false;
}
}
return true;
}
numbers = [1,2,3,4,5];
test = FindPrime(numbers);
console.log('testing', test);
In c# you can do this
String.format(5000, "$###,###,##0.00;-$###,###,##0.00;$0.00")
Which will output: $5,000
Or you can do this
String.format(-5000, "$###,###,##0.00;-$###,###,##0.00;$0.00")
Which will output: -$5,000
How do I do the same in Javascript??
UPDATE: I would also need to format a currency like this
String.format(-5000, "###.###.##0.00€;-###,###,##0.00€;0.00€")
Which would output: 5.000,00 €
you should really consider using toLocaleString so your code can rely on configuration settings like locale and currency rather than customized string format patterns.
const formatCurrency = (num, locale = 'en-US', currency = 'USD', minimumFractionDigits = 2) => {
if (isNaN(num)) {
return num;
}
return num.toLocaleString(locale, {style: 'currency', currency, minimumFractionDigits});
};
Here is an example fiddle
I Ended up rolling my own:
app.filter('formatMoney', ['$filter', function ($filter) {
return function (value, format) {
var v = format.split(';');
var index = 2;
if (value > 0)
index = 0;
else if (value < 0)
index = 1;
else {
return v[index];
}
var len = v[index].length;
var fIndex = v[index].indexOf('#');
var lIndex = v[index].lastIndexOf('0');
var f = v[index].substring(fIndex, lIndex + 1);
var symbolFirst = '';
var symbolLast = '';
if (lIndex !== len - 1) {
symbolLast = v[index].substring(len, len - 1);
}
if (fIndex > 0) {
symbolFirst = v[index].substring(0, fIndex);
}
var valueStr = value.toFixed(2).toString();
for (var i = f.length - 1; i > 0 && valueStr.length > 0; i--) {
var slice = valueStr.slice(-1);
if (f[i] === '#' || f[i].isNumeric()) {
valueStr = valueStr.slice(0, -1);
if (slice.isNumeric()) {
f = f.replaceAt(i, slice);
var j = valueStr.length - 1;
while (j > 0 && !valueStr[j].isNumeric()) {
valueStr = valueStr.slice(0, -1);
j = j - 1;
}
}
}
}
return symbolFirst + f.substr(f.search(/\d/), f.length - 1) + symbolLast;
};
}]);
Using the object and methods below, why does console.log(FizzBuzzPlus.getFizzBuzzCount(20)) print 0?
var FizzBuzzPlus = {
isFizzBuzzie: function(a) {
if(a%5 === 0 || a%3 === 0) {
if (a%5 === 0 && a%3 === 0) {
return false;
}
return true;
} else {
return false;
}
},
isFizzBuzzieChecker: function(c) {
var theFizzBuzzes = [];
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
theFizzBuzzes += i + " ";
}
}
return theFizzBuzzes;
},
getFizzBuzzSum: function(b) {
var sum = 0;
for (var i = 0; i < b; i++) {
if (this.isFizzBuzzie(i)) {
sum += i;
}
}
return sum;
},
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
return count;
}
}
};
console.log(FizzBuzzPlus.isFizzBuzzieChecker(20));
console.log(FizzBuzzPlus.getFizzBuzzSum(20));
console.log(FizzBuzzPlus.getFizzBuzzCount(20));
Some may recognize that this is FizzBuzz from Codecademy. I'm playing with the object using their online JavaScript editor. The printed result of the method is always 0. It should be returning the amount of numbers between 0 and 20 that are divisible by 3 or 5, but not both 3 and 5.
At this point in your code you have your return statement inside your for loop:
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
return count; //<-- this return is INSIDE the for loop
}
}
Move that return outside the for loop:
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
}
return count;
}
Fiddle:http://jsfiddle.net/hVf9n/
You have the return statement inside the for loop, also there is a syntax error in isFizzBuzzieChecker, where the closing ) is missing in the if condition
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
}
return count;
}
Demo: Fiddle