So I have a small JavaScript function that I need to figure out how to code, as a challenge. Basically:
function me() { // imp this function code }
var isSame1 = me("123")("321") === "123 321";
var isSame2 = me("321")("123") === "321 123";
Desired output is we want both isSame vars to be true. So from what I understand thus far, the me() function needs to return a function initially (some form of recursion I'd imagine) and then somehow a string in order to concat the resulting strings (the real example has some string manipulation during the me() function but I don't need help with that part).
I feel like there is a JavaScript feature that I am not seeing clearly here. I am aware that I can return a function as an object and call it, which is a really neat feature, but the string handling/passing to the other function and then returning it in the end is what is confusing me.
Can anyone point me in the right direction for what to look up. Don't want it to be answered completely for me, just want to be given the right research area.
Gerneio
Currying in JavaScript is quite easy. Just return a scoped function from me().
For example, to implement curried addition using a closure, you could write a function like this:
function add (a) {
return b => a + b
}
console.log(add(3)(4))
Or see below for the solution to the challenge.
Spoiler (full implementation):
function me (a) {
return b => `${a} ${b}`
}
console.log(me(123)(321))
console.log(me(321)(123))
Hope this helps you find what you're looking for.
Related
is there any way to stringify function which has function inside? I want to stringify bar function.
const foo = (x) => {
return x + x;
};
const bar = (y) => {
return foo(y)
};
bar.toString() returns
function bar(y) {
return foo(y);
}
but I want something like:
const bar = (y) => {
const foo = (x) => {
return x + x;
};
return foo(y);
};
Is it even possible? I want to use bar as follow:
// I don't have control below this line
import bar from 'bar';
`<script>(${bar})(5)</script>`
Is it even possible?
Probably. It is not, at all, simple. To do it, you'd have to use a JavaScript parser like Esprima or the ones in Babel, ESLint, etc. to parse the source code that contains both bar and foo and use the resulting AST to identify the functions that bar calls, convert those functions to source code, convert bar to source code, and insert the functions it calls into the beginning of it. And even then, depending on what those functions call and what things they use that they close over, you may have more work to do.
It's tempting to think "Well, I could just use toString on the functions and then a bit of regular expression to figure out what functions bar calls." But JavaScript source code syntax is far too complex to correctly identify function calls in a function's code with a regex or two. You need a proper parser.
As someone said in the comments (now deleted), this sounds like an X/Y problem — like you're trying to solve some other problem by doing this odd conversion of bar. I would focus on solving that problem a different way instead.
Is there a method or way in JavaScript that I can check if assert if a function returns a value through the use of an if statement?
So this:
function(val) {
if (val) return "it is true";
return "it is false";
}
versus this:
function(val) {
var str = 'it is ';
return str += val;
}
I've been looking around and can only find articles related to Java or other languages. Thanks in advance.
EDIT: I'm writing tests to assert whether or not a function (written by a user) utilizes an if statement. Hope that clarifies that a bit!
First I'd like to mention that such checks shouldn't be used in code, in which I mean that proper code should never check whether an if-statement is used inside a function. Whether a value is returned from it or not, this shouldn't be checked or tested.
But, to get back on topic. I'm not quite sure whether this is possible out of the box. I do however have a solution that you might be able to use to achieve something similar to your goals.
You can convert a given function to it's string representation. Take a look at the following example:
// Define a function
var myFunction = function() {
return 1 + 3;
};
// Print the function, as a string
console.log(myFunction.toString());
This code will print the string representation of the function in the console, so that will be function() { return 1 + 3; }. Some environments, such as the Firefox return a compiled version of the function which would look like function() { return 4; } but that doens't really have any effect on our use.
Using this method you'll be able to check whether the given function contains an if-statement. Such code would look like this:
// Define a function
var myFunction = function() {
return 1 + 3;
};
// Check whether the given function contains an if-statement
if(myFunction.toString().indexOf('if') > -1) {
console.log('This function does contain an if-statement');
} else {
console.log('This function does not contain an if-statement');
}
This method isn't ideal for your situation but it might point you in the right direction. Please note that this method isn't a rock-solid solution, at least not in this state. The usage of 'if' as a string (or something else) in a function would also cause the code above to say that the function contains an if-statement. Also, this doesn't explicitly check whether a value is returned from inside of an if-statement.
If you'd like to ensure the things mentioned above (that a real if-statement is used, in which a value is returned from it) you might have to modify the above code to make it smarter if this string-based method suits your needs. Then, I'd highly recommend to write a fancy wrapper around it to make it easier in use.
Please: only pure vanilla JS code. No jQuery or other external things, thank you. :)
How can I create a function that contains sub-functions but also returns a value if no sub-function is called?
For example, let's take a number variable num.
I want to add a round() function to the number variable; if it's called directly, I want it to round up or down depending on the variable's actual value.
var num=4.12;
num.prototype.round=function(){return Math.round(this);}
Now I wand round() to have sub-functions that will round up or down, disregarding the decimal values.
num.prototype.round.up=function(){return Math.ceil(this);}
num.prototype.round.down=function(){return Math.floor(this);}
If I do that and log num.round() to console, it does what it's supposed to. But if I log num.round.up() to console, I get an error telling me that num.round.up() is not a function.
So I try putting the sub-functions into the main function declaration like this:
num.prototype.round=function(){
var n=this;
this.up=function(){return Math.ceil(n);}
this.prototype.round.down=function(){return Math.floor(n);}
return Math.round(n);
}
Then again, num.round() will return the correctly rounded value, but both num.round.up() and num.round.down() will return "not a function" errors.
I'm going nuts trying to figure this out... I didn't only try what I mentioned above, but I also tried doing this with immediately executing functions like this:
num.round=(function(){
return function(){
var that=this;
/* anything in here is already useless because this
is no longer num's value but [Object window]... */
}
})();
I guess part of the trouble is that I'm so weak at OOP that I just have no clue about the correct terminology... naturally, that doesn't help when searching for clues or when it comes to knowing any potential reasons why something like this should not work...
So is there any way at all to do this?
Well you can pass a parameter to the function. Not the exact implementation you want, just an alternative:
var num = function (defaultNumValue) {
var delegation = {
'up': 'ceil',
'down': 'floor'
};
return {
round: function (val) {
return Math[ delegation[val] || 'round' ](defaultNumValue);
}
}
};
var sth = num(1.5);
sth.round(); // 2
sth.round('up'); // 2
sth.round('down'); // 1
May be something like:
function num(n) {
this.num=n;
this.round=Math.round(n);
this.up=Math.ceil(n);
this.down=Math.floor(n);
this.up2=function(){return Math.ceil(n);}
}
var num = new num(4.12);
alert(num.num);
alert(num.round);
alert(num.up);
alert(num.down);
alert(num.up2());
Let's say I have an object that looks like this:
{
'apple': 'nice',
'banana': 'decent',
'cherry': 'yuck',
}
and I have these two methods:
function eatItems(cherry, apple) { }
function throwItem(banana) { }
My two questions:
Is it possible for me to invoke eatItem and send the arguments in the correct order? Maybe something like:
eatItems.call(this, {'cherry': cherry, 'apple': apple});
What if I don't know what arguments eatItems receives, can I dynamically look up the names of the arguments for a function so I can know the order that I need to throw them in?
There's a way, indeed, and it involves calling toString on a function:
var source = eatItems.toString();
// => "function eatItems(cherry, apple) { }"
The next step is to parse the string you've got to get the names of the arguments:
var args = source.substring(source.indexOf("(") + 1, source.indexOf(")")),
argNames = /\S/.test(args) ? args.split(/\s*,\s*/) : [];
A few caveats:
This solution has been kept quite simple. It doesn't handle comments in the function definition.
Not every browser can correctly convert a function to a string (the PS3 browser comes to my mind), but they're a really small minority anyway.
I haven't tested it, but there may be some performance issues on slower machines and/or older browsers with large functions.
And, overall, this solution is more like an exercise. I wouldn't recommend taking this pattern in Javascript. Don't forget that some functions handle a variable number of arguments, and you won't find them listed in their definition. Rethink your code, and find a better way.
If I understand correctly you want extract the argument names from the function, and inject data from an object based on those names. This can be accomplished by converting the function to a string, extracting the arguments, and applying the function with those arguments:
function inject(data, f) {
var args = f.toString()
.match(/function\s*?\((.+?)\)/)
.pop()
.split(',')
.map(function(a){return data[a.trim()]})
return function() {
return f.apply(this, args)
}
}
var data = {
apple: 'nice',
banana: 'decent',
cherry: 'yuck',
}
var eat = inject(data, function(cherry, apple) {
console.log(cherry, apple)
})
eat() //=> yuck, nice
The obvious problem with this approach is that it is highly dependent on the variable names, so when you minify your code, the variables will get mangled and the function will stop working. This is a known problem in AngularJS, which uses something similar for their dependency injection.
This is often an XY problem, or an anti-pattern at the very least.
In Javascript, I sometimes want to return a value from a scope that isn't the current function. It might be a block of code within the function, or it might be an enclosing function as in the following example, which uses a local function to recursively search for something. As soon as it finds a solution, the search is done and the outer function should just exit. Unfortunately, I can't think of a simpler way to do this than by hacking try/catch for the purpose:
function solve(searchSpace) {
var search = function (stuff) {
var solution = isItSolved(stuff);
if (solution) {
throw solution;
} else {
search(narrowThisWay(stuff));
search(narrowThatWay(stuff));
};
};
try {
return search(searchSpace);
} catch (solution) {
return solution;
};
};
I realize one could assign the solution to a local variable and then check it before making another recursive call, but my question is specifically about transfer of control. Is there a better way than the above? Perhaps involving label/break?
Edit: since the answers to date are variations of "ew that's bad
you're not supposed to do that", let me add some necessary
context. I'm hacking on an open-source compiler that targets
Javascript. No one is going to write this code by hand, so please
don't tell me "this is a bad programming technique". What I want is a
better code generation technique. The question is whether anyone has
any clever hack for exploiting Javascript to get more flexible control
transfer.
The reason assigning the result to a local variable and checking it is
ruled out is because that requires understanding the code in a way
that is hard for a compiler to do.
It seems I stand corrected on the intent of the question. If statements are are a useful and readable way to structure code and make it flow however you want to. There's a reason goto was taken out of so many languages, because you don't need it. And it seems like, based on your example code, you're using a try-catch block as a form of goto. If you don't want certain things to run then use if statements or equivalents:
function solve(searchSpace) {
function search = function (stuff) {
//|| will only return the first value if that value is truthy, subsequent values will be ignored
return isItSolved(stuff) || (search(narrowThisWay(stuff)) || search(narrowThatWay(stuff)));
};
return search(searchSpace);
};
I know of no way to break out of function calls like you want. You can break out of loops using labels, but it doesn't seem that's much help to your situation. Other than that, I don't think JavaScript has any such ability beyond your use of exceptions
function solve(stuff) {
return isItSolved(stuff) || solve(narrowThisWay(stuff)) || solve(narrowThatWay(stuff));
}
Bob's way is good... exept that he uses twice the function statement (and that he uses ; after a function delaration without an assignment)... and that as we can do it that way, function solve actually is function search.
PS : This code will epically fail if the isItSolved, narrowThisWay or narrowThatWay functions can return a value evaluated to false as a positive result. In this cas, you would have to use ? : statement in order to check if all responses are !== undefined.
PS2: And of ourse, if these function can send an error, you have to catch it...
It looks like you're doing a fairly straightforward recursive search in your example. Why not just use "return"?
function solve(searchSpace) {
var search = function (stuff) {
var solution = isItSolved(stuff);
if (solution) {
return solution;
} else {
solution = search(narrowThisWay(stuff));
if (solution) {
return solution;
}
return search(narrowThatWay(stuff));
};
};
return search(searchSpace);
};
I suppose it could be that there are other constraints you haven't mentioned, but it's in general possible to turn any control flow into a set of nested (or recursive) functions, with appropriate return values.
The cleanest way would be to use a continuation, but you don't have that efficiently in JS (a few JS engines support continuations, but for the rest there's only CPS, which cries out for tail calls). In C, you could use setjmp/longjmp. In Common Lisp, you could use conditions (which include the functionality of exceptions plus much more). In JS, exceptions are the only non-local control flow option you have available.
You can programmatically transform a program into another that uses CPS.
function solve(searchSpace, isItSolved, isBase, narrowThisWay, narrowThatWay) {
function search(stuff, k) {
solution = isItSolved(stuff);
if (solution) {
return solution;
} else if (isBase(stuff)) {
return k();
} else {
return search(narrowThisWay(stuff), function() {
return search(narrowThatWay(stuff), k);
});
};
};
return search(searchSpace, function(val) {return val});
};
var arr=[1, 2,9,72,0,34,5,33,24,62,89,90,30,54,590,23,59,62,73];
solve(arr, function(a) {return (a.length==1 && a[0] == 5) ? a[0] : false;},
function (a) {return a.length < 2; },
function (a) {return a.slice(0, a.length / 2);},
function (a) {return a.slice(a.length / 2);}
);