typescript callback function without parameters? - javascript

I want to write some callback functions without parameters.
can anyone tell me below code is correct in typescript or javascript?
myfunction(completeCallBack, failCallBack) {
if (some_condition) {
completeCallBack;
}else {
failCallBack;
}
}

It should be:
function myfunction(completeCallBack, failCallBack) {
if (some_condition) {
completeCallBack();
} else {
failCallBack();
}
}
What you were missing is: ().
If you don't include that then the function won't be executed.
For example:
function fn(): number {
return 10;
}
let a = fn; // typeof a is () => number
let b = fn(); // typeof b is number
Edit
If your function expects two functions with no args then it shouldn't be passed functions who expects args.
You can use typescript to check for that:
type NoParamsCallback = () => void;
function myfunction(completeCallBack: NoParamsCallback, failCallBack: NoParamsCallback) {
if (some_condition) {
completeCallBack();
} else {
failCallBack();
}
}
Then, if you have a function with args but you'd like to pass it anyhow, then you can use the Function.prototype.bind function:
function logNumber(num: number): void {
console.log(`this is the number: ${ num }`);
}
myfunction(logNumber.bind(10), () => {});

Typescript is a superset of javascript. So if it's correct in javascript it sure is correct in typescript;
myfunction is not defined as a function. It's not valid in javascript. It would be valid in typescript if it would pe part of a class.
your code does nothing except evaluating some_condition. It should either call the callbacks or return them.
This is how I think it would be correct:
function myfunction(completeCallBack, failCallBack) {
if (some_condition) {
completeCallBack();
}else {
failCallBack();
}
}

Related

Can we call the parameter of a function inside of it?

I have started learning promises in JS, and there are (resolve, reject) which are passed to promise. After some actions in the function you call resolve() if there is everything OK and reject() if not. So, that's why I am asking about this.
Can we actually call the parameters of a function inside of it? Actually, if I put () after the parameter inside a function in VS Code, it is highlighted as a function.
Sorry, if there is some issues with explaining. I am not a native speaker...
There is an example: (what is stack() actually?)
const iGotIt = true;
const f = (stack, overflow) => {
if (iGotIt) {
stack({
newKnowledge: 'Finally',
message: ':)'
})
}
}
It depends on the function parameter, since it may not be a function.
For example:
myFunction(data, callback){
const result = do_something_with_data();
callback(result);
}
myFunction(0, result => {
do_something_with_result();
}); //works
myFunction(1, console.log); //works
myFunction(2, 0); //doesn't work, 0 is not a function.
what is stack() actually?
It's the first parameter in the f function.
The f function expects the first parameter to itself also be a function, and one which accepts at least one parameter which is an object.
But what stack actually is depends on what gets passed to f.
For example, consider this usage in which a function is passed as the first parameter:
const iGotIt = true;
const f = (stack, overflow) => {
if (iGotIt) {
stack({
newKnowledge: 'Finally',
message: ':)'
})
}
}
f(x => console.log(x));
Then invoking stack() invokes the function that was provided. Alternatively, consider this example:
const iGotIt = true;
const f = (stack, overflow) => {
if (iGotIt) {
stack({
newKnowledge: 'Finally',
message: ':)'
})
}
}
f();
This fails because nothing was provided, so stack is undefined. Or this example:
const iGotIt = true;
const f = (stack, overflow) => {
if (iGotIt) {
stack({
newKnowledge: 'Finally',
message: ':)'
})
}
}
f('test');
This also fails, because a string is not a function and can't be invoked like one.

JavaScript function that returns an object

This function is supposed to return an object, however, the construction used below is unfamiliar to me. How does this function work?
function expect(value) {
return {
toBe: exp => console.log(success)
}
}
This is a standard JavaScript function:
function(parameter1, parameter2) {
return returnVal;
}
But the object that is being returned looks like this:
{
toBe: exp => console.log(success)
}
Which is an object containing an ES6 arrow function, and can be alternatively expressed like so (a direct translation to an ES5 function):
{
toBe: function(exp) {
return console.log(success);
}
}
Read here for more information on ES6 arrow function notation.
I think it worth emphasizing that returns an object with a key that contains a function as a value. You can run it in the same way to run a method belonging to a class. Obliviously it fails because there is no success defined.
function expect(value) {
return {
toBe: exp => console.log(success)
}
}
let res = expect('value')
console.log(res)
res.toBe('test')
I would say that this is the intent of the code, imo this makes a lot of sense; the evaluation is done when toBe is invoked, this invokes console.log(which tests the condition, when is invoked and prints the result):
function expect(value) {
return {
toBe: exp => console.log(exp === value)
}
}
expect('value').toBe('value')
expect('notvalue').toBe('value')

javascript flexible argument for curry function

I have a question regarding curry function..
I know that if I have this simple curry function:
const greeting = (greet) => {
return (name) => {
return `${greet} ${name}`;
};
};
I can call greeting('Hello')('John') and it will return Hello John.
Is there a way to make it flexible say between 1 parameter and 2 parameters, ex: with
the above greeting function, is there a way for me to call greeting('Hello') and greeting('Hello')('John') and it will return Hello and Hello John respectively?
I know that I can do it with greeting('Hello')() and greeting('Hello')('John') but I was just trying to avoid breaking changes because I already have a greeting method and want to extend it using curry function, so I want it to also accept greeting('Hello') without the extra () at the end...
thanks
I can think of only one option that works by coercing the curried function into a string. This won't change the return value but it will allow you to get the result you want depending on context.
const greeting = greet => Object.defineProperties(
name => `${greet} ${name}`, // curried
{
toString: {
value: () => greet,
},
valueOf: {
value: () => greet
}
}
)
console.log(typeof greeting("Hello")) // function, not string
console.log(`${greeting("Hello")}`) // note the string context
console.log(`${greeting("Hello")("World")}`)
If you need the return value to actually toggle between a function and a string however, the answer is no.
In order for greeting("Hello")("John") to return a string, greeting("Hello") must return a function.
There is no way to tell within greeting() how the curried function is going to be called so you cannot detect whether or not to return a function or a string.
Think of it this way, greeting("Hello")("John") is just a short version of...
const fn = greeting("Hello")
// later or maybe never...
fn("John")
You simply don't know how, when or even if that curried function will be called.
Is there a way? Sure. But why? because won't that be "un-currying" it? And you will have to modify the function of-course.
You can always do something like this just get the output your asked for:
const greeting = (greet) => {
const split = greet.split(" ");
if(split.length > 1)
return `${split[0]} ${split[1]}`;
else return (name) => {
return `${greet} ${name}`;
};
};
If you use a helper function for currying, you can get a similar behavior automatically. For example, take the implementation at javascript.info/currying-partials
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args);
} else {
return function(...args2) {
return curried.apply(this, args.concat(args2));
}
}
};
}
You can define
const greeting = curry((greet, name) => `${greet} ${name}`)
and call
greeting("Hello", "John")
or
greeting("Hello")("John")

function that makes another function only executable once in JS

I have been working to create a function that given another function will make that second function only callable once. not unlike the _.once() function.
the desired outcome is the following:
const oneTimeFunction = _.once(function(string) { string.split(''); })
oneTimeFunction('hello')
//returns: 'olleh', and if called again it would have no effect returning the same thing a the original call.
Currently this is what I have:
_.once = function (func) {
var called = 0;
let args = null;
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments,1);
}
return function () {
if (called === 0) {
console.log('being called');
called ++;
if (!args) {
console.log('without apply');
return func.call(arguments);
} else {
console.log('with apply');
return func.apply(this,args);
}
} else {
console.log('this has been called');
return null;
}
};
};
I am running into a wall as it is returning error type undefined even with everything I have tried. Any help, even to get to where it can call the function regardless of the one time only stipulation? Thanks!
create a variable that count how much this function is called
let count = 0;
function once(str) {
if(count < 1){
count++;
return str.split("").reverse().join("");
}
else return str;
}
console.log(once("hello")); // olleh
console.log(once("hello")); // hello
console.log(once("hello")); // hello
In reading your question, I'm seeing that you would like to always return the first value on subsequent calls:
"if called again it would have no effect returning the same thing a[s] the original call."
So I believe you want to do something like this:
function computeOnce(myFn) {
let origVal = undefined;
return function (...args) {
// if this is not set, this is the first call
if (!origVal) {
// execute the function and store it's return value
origVal = myFn(...args);
}
return origVal;
}
}

Why is func undefined in this context?

So I have a function like
func()
{
const curVal = this.curVal;
const callAgain = () => { func(); };
Axios.get('somecontroller/someaction')
.then(response =>
{
const newVal = response.data.curVal;
if(curVal === newVal)
setTimeout(callAgain, 500);
else
// ....
})
.catch(response =>
{
// ...
});
}
and my browser is complaining about the line
const callAgain = () => { func(); };
saying that func is undefined. Any idea why? How can I fix?
You cannot define a function the way you posted.
However, you can for example use the function keyword to define your function:
function func() {
...
}
func(); // it works!
Edit:
According to your comment, this is a object method declaration. In order to make this work, you first need to make sure your browser supports this particular ES2015 feature or if not, you transpile it to valid ES5.
Then you should be able to access the function using this.func():
const callAgain = () => { this.func(); };
In case you are using func() e.g. as a callback for a DOM event, you also have to make sure that this is bound correctly in func, for example by explicitly binding it in the constructor:
constructor() {
...
this.func = this.func.bind(this);
}
Define the function using either of the following:
function func(){ ... }
Or...
var func = function(){ ... }
When you define it like this:
func() { ... }
JavaScript thinks you're trying to execute an existing function called func, and then run the block of code { ... }

Categories

Resources