Alternative to multiple or statements in an if block in Javascript - javascript

I have to check for
if(x == "An" || x == "Apple" || x == "A" || x == "Day" || x == "Keeps" || x == "The"....and so on){
return true;
}
else{
return false;
}
Is there a better way to write the if statement for large number of || conditions?

You could store the values in an array and then check to see if x is in the array of values using .indexOf():
Example Here
var values = ["An", "Apple", "A", "Day"];
if (values.indexOf(x) !== -1) {
return true;
} else {
return false;
}

matches = ["An", "Apple", "A", "Day"];
if (matches.indexOf(x) > -1){
return true;
} else{
return false;
}

don't do if x then true else false do simply return x. so:
var values = [...];
return values.indexOf(x) > -1;

I am no Java coder, so there may be syntactical errors, but I used the concept of what I would do in VB and then applied the syntax I found using uncle Google.
string[] SearchTerm = { "An", "Apple", "A","Day","Keeps","The" }
for(String str : SearchTerm){
if(x==SearchTerm[i]){
return true;
break;
}
else{
return false;
}
}

Related

is there a way to check if a string is of this *x.xx.xxxx* format in JavaScript?

I want a function to check if a string is of format x.xx.xxxx in javascript. For example, s.xf.ssfs should return true. And sx.xf.hsdf should return false. Also s.fsd.sfdf should return false.
Here's a reducer version
const isValid = s => s.split('.').reduce((b,a,i) => a.length === [1,2,4][i] ? b+1 : b, 0) === 3
console.log(isValid('s.xf.ssfs'));
console.log(isValid('ds.xf.ssfs'));
console.log(isValid('5.32.9850'))
For a non-regex, for loop option:
const test1 = 's.xf.ssfs';
const test2 = 'sx.xf.hsdf';
function correctFormat(str) {
if (str.length !== 9) {
return false;
}
if (str[1] !== '.' || str[4] !== '.') {
return false;
}
for (let i = 0; i < 9; i++) {
if (i !== 1 && i !== 4 && str[i] === '.') {
return false;
}
}
return true;
}
console.log(correctFormat(test1));
console.log(correctFormat(test2));
You can try using regex:
const regex = new RegExp('[a-z][.][a-z]{2}[.][a-z]{4}');
console.log(regex.test('s.xf.ssfs'));
console.log(regex.test('s.fsd.sfdf'));
As an alternative you can also split the string by periods and check the length of each individual item:
function check(s){
let a = s.split('.');
return a.length == 3 && a[0].length == 1 && a[1].length == 2 && a[2].length == 4;
}
console.log(check('s.xf.ssfs'));
console.log(check('sx.xf.hsdf'));
Regular Expressions are what you are looking for here. Simply define a regex and use the test() method to evaluate a string. For example:
const regex = /^[a-z][.][a-z]{2}[.][a-z]{4}$/
console.log(regex.test('s.xf.ssfs'))
console.log(regex.test('sx.xf.hsdf'))
If you require to accept letters and numbers you could use this regular expression instead to test against:
const regex = /^.[.].{2}[.].{4}$/
console.log(regex.test('s.5f.s9fs'))
console.log(regex.test('sx.xf.hsdf'))
From a brute force approach you could split the string by . into an array and check the length of the array, and each element within the array as follows:
let myArray = myString.split(".");
if(myArray.length !== 3){
return false
}
else if(myArray[0] !== 1 || myArray[1] !== 2 || myArray[3] != 4){
return false
}
else{return true}
Using regular expression you can achieve it.
1) This example work for letters from "a" to "z"
const format = /^[a-z]\.[a-z]{2}\.[a-z]{4}$/; //x.xx.xxxx
let test1 = format.test('s.xf.ssfs');
let test2 = format.test('sx.xf.hsdf');
console.log("test1: " + test1);
console.log("test2: " + test2);
2) This example work for letters from "a" to "z" and "A" to "Z"
const format = /^[a-zA-Z]\.[a-zA-Z]{2}\.[a-zA-Z]{4}$/; //X.Xx.xXXx
let test1 = format.test('S.Xf.sSFs');
let test2 = format.test('sx.XF.Hsdf');
console.log("test1: " + test1);
console.log("test2: " + test2);

Why does function return undefined?

So, I've recently started leaning how to code and I am trying to figure out how to create a function that will take a string and add the suffix 'ay' to the end if the conditions are met. For some reason, I keep getting 'undefined' whenever I run the function. I've tried rewriting it a few times but I keep getting something wrong and I can't figure out what it is! If someone can look this over and explain what I'm missing I would really appreciate it!
function translate(val) {
let piggy = 'ay'
let newVal = Array.from(val);
let finalVal;
let i = 0;
while (i < newVal - 1) {
if (newVal[0] == 'a' || newVal[0] == 'e' || newVal[0] == 'i' || newVal[0] == 'o' || newVal[0] == 'u') {
finalVal = newVal.join('') + piggy;
return finalVal;
} else {
finalVal = newVal;
return finalVal;
}
i++
}
}
translate('apple')
At a glance, you're subtracting a number from an array. This returns NaN and doesn't even hit the while loop. (x < NaN is always false)
Because you're not hitting the while loop the function just exists and never returns a value. That is why you receive undefined.
If you want to iterate over your newly created array, you'll want to use newVal.length.
Fixed code is as follows:
let piggy = 'ay'
let newVal = Array.from(val);
let finalVal;
let i = 0;
while (i < newVal.length - 1) {
if (newVal[0] == 'a' || newVal[0] == 'e' || newVal[0] == 'i' || newVal[0] == 'o' || newVal[0] == 'u') {
finalVal = newVal.join('') + piggy;
return finalVal;
} else {
finalVal = newVal;
return finalVal;
}
i++
}
}
translate('apple')
You're missing a return statement, and I'm not sure what you are trying to do here... Are you trying to append 'ay' to the string, if it starts with a vowel?
if yes, this is a simplified version of your code :
function translate( val ) {
if([ "a", "e", "i","o","u"].includes(val[0])) {
return val + 'ay';
}
else return val;
}

Filtering multiple input fields

I'm trying to create a filter with javascript with 4 input fields so I'm guessin 16 combinations of possible searches. I can search all 4 at once or 1 input at a time but for some reason when I add other statements I get wierd results. Is there a better way to implement a filter?
var unfilteredFloorplans = floorplanJSON.floorplanData;
filteredFloorplans = [];
for (var i = 0; i < unfilteredFloorplans.length; i++) {
if (unfilteredFloorplans[i].city == req.body.cityName &&
unfilteredFloorplans[i].building == req.body.buildingName &&
unfilteredFloorplans[i].bedrooms == req.body.minBedroom &&
unfilteredFloorplans[i].baths == req.body.maxBathroom) {
console.log(unfilteredFloorplans[i].city);
filteredFloorplans.push(unfilteredFloorplans[i]);
}
}
So now I need to write 15 more if statements? Rather than copy them in I'd like to ask if this is correct and does anyone know how you could implement this with a switch statement?
Edit: And when I say 15 more statements I mean one for if they just pick city, andother if they pick city and bedrooms etc. It just seems inefficient
A minimal fix would be to combine your "and" with "or", but note how this turns the code into a hard-to-read mess:
var unfilteredFloorplans = floorplanJSON.floorplanData;
filteredFloorplans = [];
for (var i = 0; i < unfilteredFloorplans.length; i++) {
if ((req.body.cityName == '' || unfilteredFloorplans[i].city == req.body.cityName) &&
(req.body.buildingName == '' || unfilteredFloorplans[i].building == req.body.buildingName) &&
(req.body.minBedroom == '' || unfilteredFloorplans[i].bedrooms == req.body.minBedroom) &&
(req.body.maxBathroom == '' || unfilteredFloorplans[i].baths == req.body.maxBathroom)) {
console.log(unfilteredFloorplans[i].city);
filteredFloorplans.push(unfilteredFloorplans[i]);
}
}
(BTW, this looks like a good exercise for combining conjunctions with disjunctions.)
Edit I'd recommend to put the filtering into a separate function, and to introduce an additional helper function. Also, use a more consistent naming and use "===" instead of "==".
function filterByEquality(formValue, dataValue) {
if (formValue === '') return true;
if (formValue === dataValue) return true;
return false;
}
function filterFloorplan(form, data) {
if (!filterByEquality(form.city, data.city)) return false;
if (!filterByEquality(form.building, data.building)) return false;
if (!filterByEquality(form.minBedrooms, data.bedrooms)) return false;
if (!filterByEquality(form.maxBathrooms, data.bathrooms)) return false;
return true;
}
var unfilteredFloorplans = floorplanJSON.floorplanData;
filteredFloorplans = [];
for (var i = 0; i < unfilteredFloorplans.length; i++) {
if (filterFloorplan(req.body, unfilteredFloorplans[i]);
console.log(unfilteredFloorplans[i].city);
filteredFloorplans.push(unfilteredFloorplans[i]);
}
}
You can reduce this code even further by learning about the Array.filter method. And you should fix the bug where for some fields should use ">=" or ">=" instead of "===". But I'll leave those things as an exercise.
Here's a simplified example of what your code may look like (in this example, I hardcoded the values representing the input choices):
var unfilteredFloorplans = [{
city: 'NY',
building: 'A',
bedrooms: 2,
baths: 1,
}];
var filteredFloorplans = unfilteredFloorplans.filter(
function(el) {
return el.city === 'NY' && el.building === 'A' && el.bedrooms >= 1 && el.baths >= 1;
}
);
console.log(filteredFloorplans);
The anonymous function being called inside the filter can be replaced with a named function like so:
function filterFloorplans(floorplan) {
return floorplan.city === 'NY' && floorplan.building === 'A' && floorplan.bedrooms >= 1 && floorplan.baths >= 1;
}
var filteredFloorplans = unfilteredFloorplans.filter(filterFloorplans);
You'll likely want to use this route since you can have any combination of the 4 input choices. As such, you'll want the filterFloorplans function to be "built-up" from other, smaller checks:
function testCity(userInputCity, floorplanCity) {
return userInputCity ? userInputCity === floorplanCity : true;
}
function filterFloorplans(floorplan) {
return testCity('NY', floorplan.city) && floorplan.building === 'A' && floorplan.bedrooms >= 1 && floorplan.baths >= 1;
}
This should be enough to get you started; feel free to comment if you get stuck

Determining the case (upper/lower) of the first letter in a string

In a web application, how do I determine whether the first letter in a given string is upper- or lower-case using JavaScript?
You can use toUpperCase:
if(yourString.charAt(0) === yourString.charAt(0).toUpperCase()) {
//Uppercase!
}
If you're going to be using this on a regular basis, I would suggest putting it in a function on the String prototype, something like this:
String.prototype.isFirstCapital = function() {
return this.charAt(0) === this.charAt(0).toUpperCase();
}
if(yourString.isFirstCapital()) {
//Uppercase!
}
Update (based on comments)
I don't know what you actually want to do in the case that the string does not being with a letter, but a simple solution would be to add a quick check to see if it does or not, and return false if not:
String.prototype.isFirstCapital = function() {
return /^[a-z]/i.test(this) && this.charAt(0) === this.charAt(0).toUpperCase();
}
This will work only with English alphabet.
var ch = myStr.chatAt(0);
if (ch >= 'a' && ch <= 'z') {
// small
} else if (ch >= 'A' && ch <= 'Z') {
// capital
} else {
// not english alphabet char
}
var mystring = "Test string";
var first= "";
if (mystring )
{
first= mystring[1];
}
if (first)
{
$('p').each(function()
{
if ($(this).text().charAt(0).toUpperCase() === $(this).text().charAt(0))
{
alert("Uppercase");
}
});
}
This will be called recursively until a first letter in a string is approached, otherwise returns 'no letters'.
function getFirstCase(string) {
if (string === '') return 'no letters';
var firstChar = string.charAt(0);
/*
* If both lowercase and uppercase
* are equal, it is not a letter
*/
if (firstChar.toLowerCase() === firstChar.toUpperCase()) {
return getFirstCase(string.substr(1));
} else {
return firstChar.toLowerCase() === firstChar ? 'lowercase' : 'uppercase';
}
}
Testing:
console.log(getFirstCase('alphabet'),
getFirstCase('Sunshine'),
getFirstCase('123123'),
getFirstCase('#Hi'),
getFirstCase('\nHAHA'));
I'm surprised no one's offered a regex solution to this - it seems like the easiest by far:
function getFirstCase(s) {
return (/^[\d\W]*[A-Z]/).test(s) ? 'upper' :
(/^[\d\W]*[a-z]/).test(s) ? 'lower' :
'none';
}
Blatantly stealing #Lapple's test cases:
console.log(getFirstCase('alphabet'),
getFirstCase('Sunshine'),
getFirstCase('123123'),
getFirstCase('#Hi'),
getFirstCase('\nHAHA'));
// lower upper none upper upper
See http://jsfiddle.net/nrabinowitz/a5cQa/

How do I check if a JavaScript parameter is a number?

I'm doing some trouble-shooting and want to add a check that a parameter to a function is a number. How do I do this?
Something like this...
function fn(id) {
return // true iff id is a number else false
}
Even better is if I can check that the parameter is a number AND a valid integer.
function fn(id) {
return typeof(id) === 'number';
}
To also check if it’s an integer:
function fn(id) {
return typeof(id) === 'number' &&
isFinite(id) &&
Math.round(id) === id;
}
i'd say
n === parseInt(n)
is enough. note three '===' - it checks both type and value
Check if the type is number, and whether it is an int using parseInt:
if (typeof id == "number" && id == parseInt(id))
=== means strictly equals to and == checks if values are equal.
that means "2"==2 is true but "2"===2 is false.
using regular expression
var intRegex = /^\d+$/;
if(intRegex.test(num1)) {
//num1 is a valid integer
}
example of
== vs. ===
function fn(id){
if((parseFloat(id) == parseInt(id)) && !isNaN(id)){
return true;
} else {
return false;
}
}
function fn(id) {
var x = /^(\+|-)?\d+$/;
if (x.test(id)) {
//integer
return true;
}
else {
//not an integer
return false;
}
}
Test fiddle: http://jsfiddle.net/xLYW7/

Categories