Js big switch statement, best way to do it [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 14 days ago.
Improve this question
Which of the two approaches is better in performance and memory usage?
Approach 1
const lookup = {
case1: () => { /* action for case 1 */ },
case2: () => { /* action for case 2 */ },
// ... other cases
};
switch (expression) {
case 'case1':
lookup.case1();
break;
case 'case2':
lookup.case2();
break;
// ... other cases
}
Approach 2
function lookup(caseName) {
switch (caseName) {
case 'case1':
return () => { /* action for case 1 */ };
case 'case2':
return () => { /* action for case 2 */ };
// ... other cases
}
}
lookup(expression);
Is there a better way?

You can use an object instead.
lookup_table = {
'case1': () => { console.log("case 1"); },
'case2': () => { console.log("case 2"); }
}
expression = 'case1';
lookup_table[expression]()

Related

Can this If statement be written in one line? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Is there a one line way of doing a if statement that only fires once with a boolean?
var boolean;
if (!boolean) {
function doSomething();
boolean = true;
}
Something in the lines of this.
You could take the logical OR assignment ||= with a comma operator.
boolean ||= (doSomething(), true);
It does not make much sense to do it as one line since the code is clear the way you have it written (minus your syntax error), but it can be done
function test(myBool) {
function doSomething () { console.log('run'); }
myBool = myBool || doSomething() || true;
console.log(myBool);
}
test(false);
test(true);
or if doSomething returns a true boolean or truthy value
function test(myBool) {
function doSomething () { console.log('run'); return true; }
myBool = myBool || doSomething();
console.log(myBool);
}
test(false);
test(true);

Creating an object from an array of functions from the function name [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is this a smart alternative to creating a object of functions? Benefits? Downsides?
var _ = require("underscore")
function functionName(fn){
//http://stackoverflow.com/a/17923727/340688
return /^function\s+([\w\$]+)\s*\(/.exec(fn.toString())[1]
}
function objecfify(arr){
return _.chain(arr)
.map(function(fn){
return [functionName(fn), fn]
})
.object()
.value()
}
var model = objecfify([
function create(){
return "create"
},
function read(){
return "read"
},
function update(){
return "update"
},
function remove(){
return "delete"
}
])
console.log(model)
Try to use fn.name to get function name:
var functions = [
function create(){
return "create"
},
function read(){
return "read"
},
function update(){
return "update"
},
function remove(){
return "delete"
}
];
var result = functions.map(function(fn) {
return fn.name;
});
document.write(JSON.stringify(result));

Patterns for dealing with variadic arguments in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I usually do something like the following when dealing with variadic arguments in JavaScript:
var f = function() {
var args = Array.prototype.slice.call(arguments, 0);
// ...
return something;
};
But what about doing instead:
var f = function() {
return (function(self, args) {
// ...
return something;
}(this, Array.prototype.slice.call(arguments, 0)));
};
I couldn't readily find anything addressing the pattern above, so I decided to post it here. Before I start experimenting with it, I would like to know if there are any flaws or risks I could be missing when using the rather unusual patterns described above.
I have found the pattern to be slightly less readable than the first, but it lets me write longer one-liners without declaring variables so I am growing fond of it.
Object.defineProperty(RegExp, 'join', {
value: function() {
return (function(regexes, last) {
return RegExp(regexes.map(function(item) {
return item.source;
}).reduce(function(prev, next) {
return prev + next;
}), last.slice(last.lastIndexOf('/') + 1));
}(Array.prototype.slice.call(arguments, 0),
arguments[arguments.length - 1]+''));
}, enumerable: false
});

JavaScript Module issue? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Module = (function () {
var Method = function () {
this.doSomething =function () {
return "doSomething";
};
}
return {
Method:Method
};
})();
var value=Module.Method.doSomething;
console.log(value);
New to Javascript, coming from a java background.
Why is value coming back as undefined?
Cheers.
You have to have an object of Method to access the property doSomething, you can achieve it like
Module = (function () {
var Method = function () {
this.doSomething =function () {
return "doSomething";
};
}
return {
Method:Method
};
})();
var value= new Module.Method();
alert(value.doSomething());
you can also approach it like
Module = (function () {
var Method = function () {
this.doSomething =function () {
return "doSomething";
};
}
return {
Method:new Method
};
})();
var value=Module.Method.doSomething();
alert(value);
Use as
var value= new Module.Method().doSomething();
DEMO
Module.Method is a function, apparently designed to be used as a constructor. You're also not calling the function.
var value=new Module.Method().doSomething();
^^^ create an instance of Module.Method
^^^ call the doSomething method of it.

How to make a for loop that will go through functions without going through the same one twice [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have some functions, like:
function functionOne() {
/*
code
*/
}
function functionTwo() {
/*
code
*/
}
function functionThree() {
/*
code
*/
}
How can I write code to call each of the functions, once each (i.e. without repeats), in a random order?
Put your functions in an array, randomise the array and then iterate through it:
var functions = [
function () { alert("function 0"); },
function () { alert("function 1"); },
function () { alert("function 2"); },
function () { alert("function 3"); },
function () { alert("function 4"); }
];
functions.sort(function() { return 0.5 - Math.random() });
for (var i=0;i<5;i++) {
console.log(i);
functions[i]();
}
Here's a fiddle
this function should work:
function randCall(){
var array = [1,2,3];
while(array.length > 0){
var rand = (Math.random*array.length)|0; //converts to an Integer value
switch(array[rand]){
case 1:
functionOne();
break;
case 2:
functionTwo();
break;
case 3:
functionThree();
break;
}
array.splice(rand, 1);
}
}
hope this works and helps.

Categories