Passing an array.push function in javascript - javascript

I have a problem passing an array.push function in javascript having a code like this:
const array = [];
addToArray("works", (e) => array.push(e));
addToArray("notWorks", array.push);
doConsoleLog("hello", console.log);
function addToArray(element, pushFn) {
pushFn(element);
}
function doConsoleLog(message, log) {
log(message);
}
Just curious how's that first call of addToArray works, but second causes TypeError: Cannot convert undefined or null to object. How is it possible? Type of array.push is a function. It is not possible to pass functions directly like in the case of console.log above, which works pretty well?

push is a method of array. When invoked, it uses this as a reference to the object it is being called on. If you pass it around like a normal function, you will lose that reference, the method will use the value of this defined at the moment of the call (inside addToArray, this is probably document.window), and will therefore fail.
In order to pass around a method, you need to bind it to the object you want it to operate on, in this case array. This is true for any object method in JavaScript. Function.prototype.bind() exists exactly for this purpose: it "binds" a function (in this case your method) to a given value of this, in order to work correctly.
const array = [];
addToArray("now it works", array.push.bind(array));
// or
addToArray("now it works", Array.prototype.push.bind(array));
function addToArray(element, pushFn) {
pushFn(element);
}

Once you pass a function like you did in the second case, it executes itself immediately, and array.push doesn't really mean something.
A callback function should be executed later on in the outer function.
Unlike the second example, in the first one you don't execute the function immediately, but only when you call it inside the outer function.

Your code have a lot of mistakes. What exactly should do this code? if you want to push new items in array use spread operator
const array = [...[], "works", "notWorks"]
const array = [];
addToArray("works", (e) => array.push(e));
addToArray("notWorks", array.push);
doConsoleLog("hello", console.log);
function addToArray(element, pushFn) {
pushFn(element); //function must return something
}
function doConsoleLog(message, log) {
log(message); //function must return something
}

Related

Return an array with the result of calling a method from underscore

I'm trying to recreate the functionality of the underscore _.invoke for learning purposes and I would like to really understand how it works as it seems to be something not too complicated.
The exercise is asking me to return an array with the result of calling "a" method to it. Ok, so here we start.
_.invoke = function (collection, methodName) {
let result = [];
// debugger;
if (Array.isArray(collection)) { // check if collection is an array.
for (let i = 0; i < collection.length; i++) { // iterate over collection
result.push(Array.prototype.methodName.call(collection[i]));
}
}
console.log('result:', result);
return result;
};
I don't know exactly what method is being past to methodName nor if it has any extra arguments to be forwarded (this I understand it would be used in case I'd use a method that requires args like .reduce for instance if I'm not wrong).
As I understand, when I use the .call method on methodName, it should return (push) the iterated element with the "function" applied onto it. Obviously there is something not right, I have used the debugger to see what it does on each step and once it runs the loop and arrives to the call, it quits the loop and runs to check whatever it is it does in the config file of the test.
I get this message in the error log of the HTML file:
_.invoke(mocks.arr, 'testCall').should.eql(mocks.arr);
_.invoke(mocks.obj, 'testCall').should.eql(mocks.objValuesArr);
argsArr = [mocks.arr, mocks.obj];
_.invoke(mocks.arr, 'testArgs', mocks.arr, mocks.obj);
called.should.be.true;
called = false;
argsArr = [mocks.obj, mocks.arr];
_.invoke(mocks.obj, 'testArgs', mocks.obj, mocks.arr);
called.should.be.true;
The this, thisArg and such are still a little hard for me to understand, can someone explain to me what am I missing here..?
So, after some digging, trial and error, I was totally wrong about my approach to the exercise, so I had to re-make the whole thing.
_.invoke = function (collection, methodName) {
// Spread all arguments into a variable.
let args = [...arguments];
// Since the arguments have been all passed to args, we don't need to call them as we normally would.
// Use an already defined function (_.map) with an iteratee to be passed as method.
return _.map(args[0], function (value) {
// Return the iterated value passed through the function of _.map
// and apply the rest of arguments to the element with the function from _.map if there are any.
return value[args[1]].apply(value, args.slice(2));
});
};
I don't know much about underscore.js, but I'm pretty sure _ isn't defined at all, so maybe do window._.invoke = ... instead to properly define it.

Passing an entire array from a function to another function JavaScript

I know there are lots of answers already about this query but my question is on the receiving function.
Say I have three functions:
function A(a){
var j = getList(a);
j != null? process.apply(null,j): null;
}
function getList(a){
// returns an array like array[][] with no definite size
}
// I know this function should accept multiple arguments but I want the whole array to be passed
function process(j){
// I want to loop the array here but it seems like
// the argument passed is value of array[0][0]
//
}
I know that in c, it should be:
function process(j[][]){
And python has no problem just passing j directly. Now, javascript makes me wonder how to implement this. Your help is very much appreciated.
Apply takes an array of arguments, but you are passing a single argument as an array.
There are a couple ways to solve this, one way is I just wrapped j with [j] in the apply, that way its actually passing the array as the first element in the array of arguments.
I'm sure there is a better way to explain that, but I couldn't think of it.
function A(a){
var j = getList(a);
j != null? process.apply(null,[j]): null;
}
function getList(a){
// returns an array like array[][] with no definite size
return a;
}
// I know this function should accept multiple arguments but I want the whole array to be passed
function process(j){
console.log(j);
// I want to loop the array here but it seems like
// the argument passed is value of array[0][0]
//
}
A(["1","2"]);

How to pass the method defined on prototype to Array.map as callback

I have an array
var arr = [' A ', ' b ', 'c'];
and I want to trim the spaces from each of the element from array.
It can be done by using Array.map as
arr.map(function(el) {
return el.trim();
});
I'm curious about passing the trim/toLowerCase function directly to the map as callback function, like arr.map(Math.max.apply.bind(Math.max, null)); to get the maximum element from each subarray or arr.map(Number); to cast each element to Number.
I've tried
arr.map(String.prototype.trim.apply);
but it is throwing error
Uncaught TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function
I expect that String.prototype.trim.apply should be called for each element in the array with the context set to the element from array(passed to apply);
I've also tried different combinations of apply, call and bind with no success.
Why the function on prototype cannot be referenced when using map
How function can be passed as parameter to map
arr.map(String.prototype.trim.call.bind(String.prototype.trim));
call uses this internally, which must point to the trim function to work properly in this case. Simply passing String.prototype.trim.call would leave call unbound to any method, resulting in the this value pointing to window instead.
It works, but when used apply instead of call it throws error,
arr.map(String.prototype.trim.apply.bind(String.prototype.trim));
The problem is that map will pass 2 arguments, the item and the index. Therefore it ends up calling something like 'String.prototype.trim.apply('test', 0) which fails since the second argument must be an array.
one more thing [' A ', ' B ',
'c'].map(String.prototype.trim.call.bind(String.prototype.toLowerCase));,
in this, I've used trim.call and passed toLowerCase as context then
why we need trim here, why trim is not called
When using call.bind the path that you chose to access the call function reference becomes irrelevant. The function that will get called is the one that is bound.
If you want to compose functions together you will need a different approach:
var call = Function.prototype.call,
trim = call.bind(String.prototype.trim),
toLowerCase = call.bind(String.prototype.toLowerCase),
trimAndLowerCase = pipelineFrom(trim, toLowerCase);
[' TeST '].map(trimAndLowerCase);
function pipelineFrom(fn1, fn2) {
return function (val) {
return fn2(fn1(val));
};
}
However at this point you're better off with:
arr.map(function (val) {
return val.trim().toLowerCase();
});
This works, it sure is long-winded though:
var t = String.prototype.trim.call.bind(String.prototype.trim);
arr.map(t);
Because it's longwinded there are blog posts and modules devoted to uncurrying, which is what you are trying to do here.
I did ask about this here once...

Call a function with a variable number of arguments in JavaScript (similar to call())

I'm familiar with the way call(), which you can pass a variable number of arguments that will be loaded into a function's parameters when called. I'm trying to do something related where I recurse through nested set objects in RaphaelJS with forEach (analogous to jQuery's each), determine whether the child element is another set, and apply a function with a variable number of arguments if not. I want to make it generic so that I can apply any function, but make the functions that I pass have simple parameter constructors without having to access the arguments property of the function.
function recursiveFncApply(set, fnc, args) {
set.forEach(function(item) {
if (item.type == 'set') {
recurseApplyFncToSets(item, fnc, args);
} else {
fnc(item, args);
}
});
}
function translateOperation(element, operation, x, y)
// do stuff to element with operation, x, and y args without accessing
// accessing arguments property
}
recursiveFncApply(passedSet, translateOperation, [arg1, [arg2, ...]]);
I want to do this so that I can use multiple functions without having to repeat myself with code that determines arguments and properly assigns them before usage. I'm not sure whether there's some kind of functionality or language utility that I'm missing that would enable me to do this, or somehow to programmatically "construct" a function call from the remaining arguments passed to recursiveFncApply. Is this possible in JavaScript?
Clarification: I want to pass a variable number of arguments to my recursive function that will be passed to any function that I want to be applied to the contents of the sets my recursive function is working on. So I want to be able to make recursiveFncApply work generically with any function while still using an argument structure that works like a function being executed via call().
Say I have another function in addition to translateOperation:
function anotherFunction(element, differentArg) {
// do something with one argument
}
Ideally I could then use my recursiveFncApply in this way:
recursiveFncApply(passedSet, translateOperation, operation, x, y);
recursiveFncApply(passedSet, anotherFunction, singleArg);
As well as this way:
recursiveFncApply(passedSet, anotherFunction, singleArg);
I believe that this is similar to how call() works in that I could do:
anotherFunction.call(this, element, differentArg);
.. without having to change the structure of anotherFunction to sort out the arguments property, or pass an object/array.
It turns out that Felix King had the right idea/was the closest. I found a direct answer to my question as soon as I realized what I was actually trying to do, which is pass forward arguments from function to function (found the answer here). So I got this to work with this code:
function recursiveSetFncApply(set, fnc/*, variable */) {
var me = this;
var parentArgs = arguments;
set.forEach(function(element) {
if (element.type == 'set') {
parentArgs[0] = element;
me._recursiveSetFncApply.apply(me, parentArgs);
} else {
// Generate args from optional arguments and pass forward; put element in args at front
var args = Array.prototype.slice.call(parentArgs, 2);
args.unshift(element);
fnc.apply(element, args);
}
});
}
I make a reference to arguments with parentArgs because I need to update the set property in arguments before I pass it forward to the next recursive loop, otherwise I hit an infinite loop because it hasn't updated at all because it's using the original arguments set. I was under the impression that apply() will not actually pass forward arguments, but simply pop an array into the new function that you have to access by index--this isn't the case. When I used apply() on translateElementOperation, I had all the arguments I needed in their exact places. Here's the updated function I ran through the recursive apply:
function translateElementOperation(element, operation, x, y) {
var currentPath = element.attr('path');
translatedPath = Raphael.transformPath(currentPath, [operation, x, y]);
element.attr('path', translatedPath);
}
Thanks for the help, everyone!
Use .apply instead of .call
functionName.apply(element, [any, number, of, variables, ...]);
// instead of this
functionName.apply(element, set, of, variables, ...);
This is more useful like so:
var fnVars = [];// fill this anyway you want.
functionName.apply(element, fnVars);

jshashtable.each use existing function

So I have a Hashtable defined (with jshashtable.js):
hashy = new Hashtable();
I put some keys in it:
hashy.put("hi", "yay");
hashy.put("hello", "yes");
Now I want to iterate it with .each, as the doc says:
hashy.each(iterator());
But it says 'object is not a function'
Now, if I do this:
hashy.each(function() { });
It works, but is there a way to call an existing function this way?
I just realized the most obvious answer would be to do:
hashy.each(function() { iterator(); });
Assuming your iterator function is something like the following:
function iterator(key, value) {
// Do something with key and/or value
}
... then just pass the function in without the parentheses. With the parentheses, you're executing the function immediately (just once) and passing the returned value into each(), which is probably not what you intended.
hashy.each(iterator);

Categories