Unexpected variables in arguments[] when passing a function - javascript

I have two files in a folder - index.js and util.js with their code base as follows
Util.js
let obj = {}
obj.sendTransaction = () => {
console.log(arguments);
return new Promise((resolve, reject) => {
// try {
// let data = ethFunction.call()
// resolve(data)
// } catch (e) {
// reject(e)
// }
});
}
module.exports = obj
In Index.js, if I pass arguments to addNewParticipant or its variation then they do not turn up in the arguments object in util.js, for instance
const addNewParticipant = (foo, bar) => {
var ethFunction = myContract.addParticipant.sendTransaction
console.log(ethFunction);
EthUtil.sendTransaction()
}
const addNewParticipantTwo = (foo, bar) => {
var ethFunction = myContract.addParticipant.sendTransaction
console.log(ethFunction);
EthUtil.sendTransaction(ethFunction, foo, bar)
}
and call it such addNewParticpant(1, 2) and , addNewParticpantNew(1, 2) the numbers 1 and 2 do not show up in the arguments object in the util function. In fact, the arguments object remains the same, 4 inputs describing some functions and files in node_modules including Bluebird and a reference to index.js itself
My final aim is to
Pass a function from index.js to util.js
Pass along unknown number of variables
Call the passed function and apply the unknown number of variables to it
Wrap the whole thing in a promise and do some data validation
Ideally arguments[0] would represent a function I would pass and the other would be the values. I would then use
var result = arguments[0].apply(null, Array().slice.call(arguments, 1));
If it helps, the function I want to pass has an optional callback feature

As already mentioned in the comment, fat arrows don't have their own this or arguments objects. The arguments object you're logging is from the function created by the module loader, and its passed arguments.
You can either use a "regular function", or in this case, you can use a ...rest parameter
And, avoid the Deferred antipattern.
//first a little utility that might be handy in different places:
//casts/converts a value to a promise,
//unlike Promise.resolve, passed functions are executed
var promise = function(value){
return typeof value === "function"?
this.then( value ):
Promise.resolve( value );
}.bind( Promise.resolve() );
module.exports = {
sendTransaction(fn, ...args){
return promise(() => fn.apply(null, args));
}
}

Related

Writing memoize function without ES6 syntax

I am working on a problem and I am not allowed to use ES6 syntax so I can't use the spread/rest operator. How can I write a function that will take any number of arguments without a spread/rest operator?
function memoize(func) {
var cache = {};
return function (...args) {
if (args in cache) {
return cache[args];
} else {
cache[args] = func(...args);
return func(...args);
}
};
};
Firstly you have to use the arguments object. It is an older feature which makes a variable called arguments available in non arrow functions. The value of arguments is all the arguments a function receive. It is an array-like object, not an array. This eliminates the use of rest operator.
Also, it is better to create a key, when you are creating a generic function.
Why? Javascript object keys can only be string. If an object is used as a key it gets auto converted to a string : [object Object]. So basically all your object keys will override each other. Here is a demo:
const obj1 = { a : 1};
const obj2 = { b : 2};
const x = {};
x[obj1] = 2;
console.log(x);
x[obj2] = 2;
console.log(x);
To generate hash key you could use any method. Below is not a bullet proof implementation but I have just joined all the arguments into a . separated array.
Now we have to call your function with these arguments, in the else condition. How? When you want to forward you arguments to another function, and they are in the form of an array, you can use something like apply. It is pre ES6 feature which lets you run a function in a different context, or lets you pass arguments as an array. Here we won't be changing the context, but the second use case is what we will be using.
function memoize(func) {
var cache = {};
return function () {
const key = Object.values(arguments).join('.');
console.log(arguments);
console.log(cache);
if (key in cache) {
return cache[key];
} else {
cache[key] = func.apply(null,arguments);
return cache[key];
}
};
};
const conc = (str,str2,str3) => `${str}_${str2}_${str3}`;
const memoizedSq = memoize(conc);
memoizedSq('hello','hi','hey');
memoizedSq('bye','see you','so long');
memoizedSq('hello','hi','hey');
I have used join to create the string.
Minor optimization I did by changing your code in the else condition is not calling function multiple times. I just saved it in the object and returned the same value.
Note: This could break for cases where if a function takes a string, and the string itself contains ..

passing function with args to another function in javascript

I'm brushing up on knowledge of Javascript and filling in some of the gaps.
for the memoize function, I get why it would console log the function as the memoizeSomeFunction const is just a function expression of someFunction being passed into memoize as an arg. what I can't seem to conceptualize is how the arg being passed into memoizeSomeFunction gets to the return part of the function. can someone elaborate?
const memoize = (fn) => {
console.log(fn);
return (arg) => {
console.log(arg)
}
}
const someFunction = (x = 0, y = 0) => {
return `x is {$x} y is ${y}`;
}
const memoizeSomeFunction = memoize(someFunction);
memoizeSomeFunction(1)
The memoize() function returns a function:
(...args) => {
console.log(...args)
}
That function collects its arguments into an array using the spread (...) syntax, and then un-collects them the same way in the console.log() call.
Thus when you call the function returned from memoize(), it simply logs the arguments passed.
To summarize:
Just one argument is passed to memoize(), your someFunction() function;
The memoize() function returns another function, and that function logs its arguments (and otherwise does nothing with someFunction());
The function source is logged when memoize() is called, and the argument list to the return value from that is logged whenever it is called. If you added another call to that returned function, you'd see those arguments logged separately.
// ES5 equivalent:
const memoize_es5 = function(fn) {
// fn is closured and can be used
// function returned, when it will be called we will have call arguments as well
return function () {
console.log(fn.apply(null, arguments));
}
}
const memoize = fn => (...args) => console.log(fn(...args));
const someFunction = (x = 0, y = 0) => {
return `x is ${x} y is ${y}`;
}
const memoizeSomeFunction = memoize(someFunction); // function received as result of memoize call
memoizeSomeFunction(1, 15); // pass arguments to that function function
// ...args in the arguments is a rest operator
// it just capture all rest arguments into an array:
((first, ...args) => console.log(first, args))(1, 2, 3)
// ...args in a function call is spread operator
// it spreads an array into parameter list:
console.log(...['spread', 'operator'])

How to test the result of a curried function in Jasmine?

Use Case:
I have a module of functions, each function is unit tested
I have a factory function that creates a stream of these functions that a third party library requires.
I would like to test that this factory function produces the correct stream. Using #cycle/Time, I am able to create the stream and assert on the stream.
I am able to assert that the functions appear on the stream in the correct order.
However, I am unable to assert on any function that is curried. How would one assert on curried functions?
Currently, I have a hack in place to JSON.stringify the functions and assert on their source.
To simplify the problem, I created a simple test suite so we aren't concerned with using #cycle/Time. It appears that curried functions are new instances of the function. Please see the code below.
I was wondering how would I be able to make the failing test pass? In this case I simulate the curried function by using bind. Is this possible?
const a = () => b
const b = () => {}
const c = (arg) => b.bind(null, arg)
const d = () => () => {}
describe("curried function test", function() {
it('should return a reference to b', () => {
expect(a()).toBe(b)
})
// This test fails because b.bind returns a new function.
it('should return a reference to a curried b', () => {
expect(c('foo')).toBe(b)
})
it('should create a new instance everytime', () => {
expect(d()).not.toBe(d())
})
});
I've setup a jsfiddle here.
"This test fails because b.bind returns a new function."
That's because what you get from c is the result from b.bind(null, arg), which isn't the same as b.
Otherwise, b.bind would be modifying b.
As mdn says:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
(source, emphasis mine)
Basically, c can't return a reference to b.
What you do have, is the resulting function's name:
const b = () => {};
const c = (arg) => b.bind(null, arg);
const e = c("foo");
console.log(e.name);
console.log(e.name === `bound ${b.name}`);
So, you could test that e.name equals "bound " + b.name.

Why pass an undefined javascript function parameter?

So I'm learning Javascript and I see this code:
var apple = {//... an object with some properties};
var fruit = apple.someMethod(function (b) {return b.a_property_of_apple});
Where someMethod and a_property_of_apple are valid methods and properties.
My question pertains to the argument, b, of the anonymous function which is not declared or defined anywhere else:
function (b) {return ...
What is going on here? What is b and why is it being used?
Apologies in advance for the basic nature of the question. If someone just wants to drop some focused terms on me to read up on that would be great short of an explanation.
The anonymous function is a callback function being passed to the apple.method() invocation.
apple.method() will invoke that anonymous function at some point during it's execution, ( or pass it to another function ). Whenever it's invoked it will be invoked with an argument that will be available inside the callback. You could call it b, or response, or whatever you want (logical names are best) and be able to use it within the anonymous function.
You should read about Callback functions over at MDN.
EDIT: I will explain the parts to you
var apple = {} This is the definition of an object
var fruit = apple.someMethod(function (b) {return b.a_property_of_apple}); is defining that fruit is equal to the return value of the invocation of apple.someMethod(...)
apple.someMethod(function (b) {return b.a_property_of_apple}); is the invocation of apple.someMethod with function (b) {return b.a_property_of_apple} as the only argument.
The b argument in the anonymous function function (b) {return b.a_property_of_apple} will be passed to it's invocation within the apple.someMethod.
Here is an example snippet.
// define apple
var apple = {
// define method
someMethod: function( callback ) {
var obj = {
a_property_of_apple: "Eat me!" // this will be returned
}
// return the invocation of callback with obj as argument
return callback(obj);
}
}
var fruit = apple.someMethod(function (b) {return b.a_property_of_apple});
console.log(fruit);
EDIT: Ok, going to use something slightly less abstract as an example.
// notice employees being passed to this function
// that is called an argument and is usable inside the function
var orginization = function( employees ) {
// this will take the empoyees argument and assign it to this.employees
// or set this.employees to an empty array if there is no employees argument
this.employees = employees || [ ];
// this is a method ( a method is a function on an object )
// this function takes 3 arguments
this.addEmployee = function( employee ) {
// we use the 3 arguments to push a new object with title, name, and salary
// properties provided by the function arguments
this.employees.push( employee );
}
// this method returns the value stored in this.employees
this.getEmployees = function() {
return this.employees;
}
}
// this is a variable an array of employees only containing 1 employee
// i will use it in the creation of my new orginization
var employess = [
{
title: "CEO",
name: "Enola",
salary: "$$$$$$$"
}
];
// i use the new to create learningInc from originization( employees )
// originization is a constructor function which creates an object
// with methods and properties found on the constructor
var learningInc = new orginization( employess );
// console.log learningInc.getEmployees() an you will see still only the CEO
// works here
console.log( "before newHire: ", learningInc.getEmployees() );
// lets make a newHire
var newHire = {
title: "Peon",
name: "Sadly McFrownFace",
salary: "$"
};
// add the newHire to the employess of learningInc wth out getEmployees() method
learningInc.addEmployee( newHire );
// log the new value of learningInc.getEmployees and you see we now have 2 employees
console.log( "after newHire: ", learningInc.getEmployees() );
Ok now notice this line var learningInc = new orginization( employess );
The employees variable I'm passing to this function as an argument is used in this function var orginization = function( employees ) { ... }.
Hope this help.
My question pertains to the parameter, b, of the anonymous function which is not declared or defined anywhere else: What is going on here?
What is b and why is it being used?
Why you say it is not declared? It is declared right there. Consider this simple JavaScript function:
function doSomething(a, b){
//do something here;
}
In this code, we are creating a function, naming it "doSomething", and declaring two parameters for it a and b. This is how we declare function parameters in JavaScript. Now your example:
function (b) {return ...
is exactly the same, except we didn't give this function a name, which means it is an anonymous function. That's the only difference, but its parameter b is declared right there like any standard function. So there is nothing special going here, it's a standard function parameter and used as such.
There are a couple concepts at work here
Function declarations vs function expressions; you can use function as an operator to define a function, and assign the function to an identifier and pass it around like any normal object
Callbacks; you can pass a function CB into another function A to be called by A (as defined by A)
Passing something without an identifier
Function Declaration
// declare function
function foo(argFoo) {
console.log('foo', argFoo);
}
// invoke function
foo('was declared'); // "foo" "was declared"
Function Expression
// express function
var bar = function (argBar) {
console.log('bar', argBar);
};
// invoke function
bar('was expressed'); // "bar" "was expressed"
Callbacks
function fizz(callback) {
console.log('first I fizz');
callback();
}
function buzz() {
console.log('then I buzz');
}
fizz(buzz);
// "first I fizz"
// "then I buzz"
Passing without an Identifier,
Basically, defining things in-place
// say we have some fn fizzbuzz
function fizzbuzz(foo) {
console.log(foo);
}
// we could pre-define what we want to pass to it
var i = 1;
fizzbuzz(i); // 1
// or we could pass directly
fizzbuzz(1); // 1
// with anything we like
fizzbuzz({some: 'object'}); // {some: "object"}
// even a function
fizzbuzz(function () {}); // function () {}
Maybe if I break down what is happening into more readable code, you can see what is happening.
someMethod is a method that take a function as an argument. This is more easily seen when broken down like below.
It's up to someMethod to determine what they do with that function. In this example, I am executing the function being passed into someMethod and passing it my this context.
var apple = {
name: 'Apple',
someMethod: function(func) {
return func(this);
}
};
function getName (b) {
return b.name;
};
const name = apple.someMethod(getName); // Apple
To your question: b is defined as the first argument to your anonymous function. This is more clearly expressed when the code is broken out above. But you could also express it like this:
const name = apple.someMethod(function(x) { return x.name; }); // Apple
or like this using ES6:
const name = apple.someMethod(x => x.name); // Apple

How to use 2 arguments in a 1-arg javascript function?

I am using the http module in node.js to read from url. The http.get function has this signature:
http.get(options[, callback])
The callback function takes a single argument, res. What can I do if I want to use extra objects/functions inside the callback? I can think of inlining the get call like so:
outerFunction = function(xyz) {
http.get(options, (res) => {
// do stuff with xyz here
xyz(res.blah);
}
});
But if my callback gets long I want to declare it upfront somewhere:
myCallback = function(xyz) {
return function(r) { xyz(r.blah); };
}
And invoke myCallback like so:
outerFunction = function(xyz) {
http.get(options, (res) => {
myCallback(xyz)(res);
});
}
But that seems super clumsy and only to get around the 1-arg callback restriction.
Are there better ways? Thanks!
you can use this code please,because myCallback return a function,then after get the resource,http will pass the res into xyz automatically.
outerFunction = function(xyz) {
http.get(options,myCallback(xyz));
}
You could use the arguments object.
The arguments object is a local variable available within all
functions. You can refer to a function's arguments within the function
by using the arguments object. This object contains an entry for each
argument passed to the function, the first entry's index starting at
0.
Quick example:
function test1234(a){
var args = arguments;
console.log(args); // prints -> 0: "a", 1: "b"
}
test1234('a', 'b');

Categories