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
});
Related
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);
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 4 years ago.
Improve this question
I can't seem to wrap my head around the logic for writing a function that looks something like eight(times(five)) in JavaScript.
Example:
eight(times(five)) should return 40
three(plus(two)) should return 5
It was a Codewars problem. It provided empty functions for numbers 0-9 that looked like "eight( ){ }" as well as empty functions for operators that looked like "times( ){ }." The solution should be such that executing "eight(plus(three))" would return 11, etc.
You could use a function which returns either a value or a function call with the actual value. Then you nee a function for the operand which retuns a closure over the function for the value.
function eight(fn) {
return typeof fn === 'function' ? fn(8) : 8;
}
function times(fn) {
return function (op) {
return fn() * op;
};
}
console.log(eight(times(eight)));
I know the question got answered while i was writing this reply...but i will post it anyways.
function times(fn) {
return function (op) {
return fn() * op;
};
}
function plus(fn) {
return function (op) {
return fn() + op;
};
}
function minus(fn) {
return function (op) {
return fn() - op;
};
};
createNumbers = () => {
var num = 0;
['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'].forEach((number) => {
let val = num;
window[number] = (fn) => {
return fn ? fn(val) : val;
};
num++;
});
};
createNumbers();
three(times(five)); // 15
eight(plus(two));// 10
etc
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to convert a string into a function without using eval(), however whenever I pass the function name into the window object and check its type. Javascript does not seem to recognize it as a function. I always get this custom error message I've defined in the else statement: "Could not find function: 1->validateLogin".
My dom_ready prototype:
dom_ready: function (inputFunc) {
document.addEventListener("DOMContentLoaded", function () {
try {
inputFunc();
} catch (e) {
DN.errors.push(e.message);
}
});
},
function show_pass() {
...
}
function validateLogin(k) {
...
}
DN.DOM.dom_ready(function () {
var event_ids = [
["#login-form-dialog", "validateLogin", "submit", 1]
["#loginnotes", "validateLogin", "click", 1],
["#loginnotes2", "validateLogin", "click", 2],
["#show-pass", "show_pass", "click", ""],
]
for (var i = 0; i < event_ids.length - 1; i++) {
var fN = window[event_ids[i][1]];
if (typeof fN === 'function') {
$(event_ids[i][0]).on(event_ids[i][2], function () {
fN(event_ids[i][3]);
})
} else {
console.log("Could not find function: " + i + "->" + event_ids[i][1]);
}
}
});
The particular syntax error causing your problems was addressed in other answers. To find such syntax errors, look at the console for errors. Or, run your code through a linter. Otherwise, you will have to post to SO every time you forget a comma, which does not seem to be a very scalable approach.
More basically, do not pass around function references using strings giving their names, which you need to then look up on the window object. Instead, just pass the function reference itself (validateLogin). Unlike some other languages, in JS functions are first-class citizens which can be referred to and passed around as themselves. Your code would look like this:
DN.DOM.dom_ready(function () {
var event_ids = [
["#login-form-dialog", validateLogin, "submit", 1]
^^^^^^^^^^^^^
...
for (var i = 0; i < event_ids.length - 1; i++) {
var fN = event_ids[i][1];
Of course, you will have to make sure that validateLogin is visible at the time this ready function is executed.
However, you have a more basic problem which will prevent your code from running properly, in the following lines:
$(event_ids[i][0]).on(event_ids[i][2], function () {
fN(event_ids[i][3]);
})
Here, the anonymous function is a closure over the variable i, and at the time it is executed (when the event occurs), i will already be at its maximum value of 3. There are many questions and answers on this topic here on SO, but the easiest solution is to use for (let i, if you are working in an environment that supports let. Otherwise, see questions like this one.
You are missing a comma after the first item in event_ids:
var event_ids = [
["#login-form-dialog", "validateLogin", "submit", 1], // <-- missing comma
["#loginnotes", "validateLogin", "click", 1],
["#loginnotes2", "validateLogin", "click", 2],
["#show-pass", "show_pass", "click", ""],
]; // <-- also it is better practice to have semi-colon here
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.
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 9 years ago.
Improve this question
// set Process
i18n.setProcess(function() {diFunctions.getI18n('http://localhost/service/i18n/page?lang=eng&group=staff') });
// Setter and getter
this.setProcess = function( opProcess ) { //here param opProcess is function with parameters see i18n.setProcess() line of code
if( opProcess == undefined)
throw "Process is undefined";
if( $.isFunction(opProcess) == false )
throw "Process is not a function"
process = opProcess;
};
this.getProcess = function() {
return process;
};
See how i18n.setProcess passes a function with param as a parameter to setProcess.
Now i what i want in SetProcess is function() {diFunctions.getI18n('http://localhost/service/i18n/page?lang=eng&group=staff',**id**) // id is added dynamically to the function itself which was passed as parameter to setProcess
Problem - I want to add id dynamically(defined in my class variable always accesible by id) on set process with addition to functions parameter(Url,etc,etc,id). Functions parameters can grow but the id should be added last as a parameter?
Tried quite a few solutions but didnot work out? Check here
This is what the arguments object is for..
function foo() {
var lastArg = arguments.length ? arguments[arguments.length - 1] : 'default';
return lastArg;
}
foo(); // "default"
foo(1); // 1
foo(1, 2); // 2
If you want to write a function similar to bind which only sticks arguments on the end then you could do
function appendArguments(fn) {
var slice = Array.prototype.slice.call.bind(Array.prototype.slice),
args = slice(arguments, 1);
return function () {
return fn.apply(this, slice(arguments).concat(args));
};
}
now
var bar = appendArguments(foo, 3);
bar(); // 3
bar(4, 5); // 3 (because it's calling `foo(4, 5, 3)`