How to generate different spawn points for objects (Javascript)? [duplicate] - javascript

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
Whats the prettiest way to compare one value against multiples options?
I know there are loads of ways of doing this, but I'm looking for the neatest.
i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):
if (foobar == (foo||bar) ) {
//do something
}

Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}

What i use to do, is put those multiple values in an array like
var options = [foo, bar];
and then, use indexOf()
if(options.indexOf(foobar) > -1){
//do something
}
for prettiness:
if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this :)
}
and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}

Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.

You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}

Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}

Why not using indexOf from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.

(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.

I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).
However, there is a similar way by using jQuery with the $.inArray() function :
if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
alert('value ' + field + ' is into the list');
}
It could be better, so you should not test if indexOf exists.
Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

Related

Does this simple way of writing multiple conditions on an if exist? [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
Whats the prettiest way to compare one value against multiples options?
I know there are loads of ways of doing this, but I'm looking for the neatest.
i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):
if (foobar == (foo||bar) ) {
//do something
}
Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
What i use to do, is put those multiple values in an array like
var options = [foo, bar];
and then, use indexOf()
if(options.indexOf(foobar) > -1){
//do something
}
for prettiness:
if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this :)
}
and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
Why not using indexOf from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.
I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).
However, there is a similar way by using jQuery with the $.inArray() function :
if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
alert('value ' + field + ' is into the list');
}
It could be better, so you should not test if indexOf exists.
Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

Do While Loop exits despite condition being met [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
Whats the prettiest way to compare one value against multiples options?
I know there are loads of ways of doing this, but I'm looking for the neatest.
i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):
if (foobar == (foo||bar) ) {
//do something
}
Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
What i use to do, is put those multiple values in an array like
var options = [foo, bar];
and then, use indexOf()
if(options.indexOf(foobar) > -1){
//do something
}
for prettiness:
if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this :)
}
and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
Why not using indexOf from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.
I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).
However, there is a similar way by using jQuery with the $.inArray() function :
if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
alert('value ' + field + ' is into the list');
}
It could be better, so you should not test if indexOf exists.
Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

Is it possible to create an if statement in this sort of way? [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
Whats the prettiest way to compare one value against multiples options?
I know there are loads of ways of doing this, but I'm looking for the neatest.
i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):
if (foobar == (foo||bar) ) {
//do something
}
Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
What i use to do, is put those multiple values in an array like
var options = [foo, bar];
and then, use indexOf()
if(options.indexOf(foobar) > -1){
//do something
}
for prettiness:
if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this :)
}
and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
Why not using indexOf from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.
I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).
However, there is a similar way by using jQuery with the $.inArray() function :
if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
alert('value ' + field + ' is into the list');
}
It could be better, so you should not test if indexOf exists.
Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

Fast way to check if a javascript array is binary (contains only 0 and 1)

What is a quick way to determine if an array is only composed of 0's and 1's?
I'm vaguely familiar with a boolean solution but am not away how to implement it. In order to implement is you would have to assign values to the boolean
true = 0
and
false = 1
But how would you implement this if you are given an array such that
array = [1,1,1,1,0,0,0,0]
isArrayBool (){
}
Very very naive solution:
function isArrayBool(array) {
for (var i of array) {
if (i !== 0 && i !== 1) return false;
}
return true;
}
console.log(isArrayBool([1,0,0,0,1])); // true
console.log(isArrayBool([1])); // true
console.log(isArrayBool([2,3,0])); // false
So I threw a few functions together in jsperf to test. The fastest one I found so far is the one below (which is much faster than the for of version):
function isBoolFor(arr) {
for(var i=arr.length-1; i>=0; --i){
if(arr[i] !== 0 && arr[i] !== 1) return false
}
return true
}
Comparison is here
EDIT: I played around with another version that turned out to be quicker:
function isBoolFor(arr) {
for(var i=0; arr[i] === 0 || arr[i] === 1; i++){}
return i === arr.length
}
The key here is that because most of the array you are checking will consist of zeros and ones, you can avoid doing two boolean checks every iteration by using the || instead of the && negative check. It is only a subtle improvement, and could be argued to be no better than the one above in practicality.
UPDATE: So the difference between all the for and while variants is too subtle to declare an overall winner. So in that case I would go for readability. If you want binary use typed arrays!
FINAL UPDATE:
I was curious and wanted to find an even faster version, and it can be done if the array is known to be only numbers. If the array contains only numbers, then you can use a bitwise operator check for either of the values in question. For example:
function isBoolFor(arr) {
const test = ~0x01
for(var i=arr.length-1; i>=0; --i){
if(test & arr[i]){ return false }
}
return true
}
https://jsperf.com/bool-array-test-2/1
As we can see here, the fastest way to do this can be seen here... With a simple for loop, as suggested by user Jaromanda in a comment. This for loop blows other solutions out of the water in terms of speed.
var someArray = [1,0,1,1,1,1,0,0,1,0,1,0,0,1,0,1,0,1,1,1,1,0,1,1,0,1,0];
function simpleForLoop(array){
var numArgs = someArray.length;
for(var loop = 0; loop < numArgs; loop++){
var arg = someArray[loop];
if(arg !== 0 && arg !== 1){ return false; }
}
return true;
}
var isbool = simpleForLoop(someArray);

How can you shorten ||? [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
Whats the prettiest way to compare one value against multiples options?
I know there are loads of ways of doing this, but I'm looking for the neatest.
i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):
if (foobar == (foo||bar) ) {
//do something
}
Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
What i use to do, is put those multiple values in an array like
var options = [foo, bar];
and then, use indexOf()
if(options.indexOf(foobar) > -1){
//do something
}
for prettiness:
if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this :)
}
and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
Why not using indexOf from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.
I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).
However, there is a similar way by using jQuery with the $.inArray() function :
if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
alert('value ' + field + ' is into the list');
}
It could be better, so you should not test if indexOf exists.
Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

Categories

Resources