How to execute multiple functions from object? - javascript

I want to call all functions that are located within object.
const data = {
fruits: funcA(),
vegetables: funcB(),
bread: funcC(),
}
Result I want to get is:
firstFunc();
dispatch(funcA());
dispatch(funcB());
dispatch(funcC());
someMoreFunctions();
My code is:
firstFunc();
// I need to somehow execute here all functions from object just like in example above
someMoreFunctions();
I realised it's worth mentioning that I want to pass those functions to child component that will execute them once clicked on:
<Component onClick={()=>{
firstFunc();
// I need to somehow execute here all functions from object just like in example above
someMoreFunctions();
}}

You can iterate through each value of the object, and, if it is a function, call it:
const data = {
fruits: () => console.log('some fruits'),
vegetables: function B() { console.log('more vegetables') },
bread: (function () { return () => console.log('less bread') })(),
pasta: 'No'
}
Object.values(data).forEach(v => typeof(v) == 'function' ? v() : null)

Defining the function:
const object = {
function: () => console.log("You can use functions like this!"),
anotherFunction: log()
}
function log (){
console.log("Yet another way of doing this 😎");
}
Calling the Function:
object.function;
object.anotherFunction;
Remember that when calling the function you shouldn't use the parenthesis

Related

How do I get my mocha/chai test to have arguments refer to the arguments of myFunction and not something else?

I'm trying to test a function with mocha/chai. I'm new to test driven development, so I'm surely referring to a thing or two incorrectly. Feel free to correct me :)
Here's my function:
export const myFunction = (s1, s2) => {
if (arguments.length !== 2) {
return {
success: false,
errorMessage:
'Be sure to include 2 arguments. Both arguments should be strings.',
};
}
const returnObj = {};
// rest of the function...
return returnObj;
};
And here's my test:
import { expect } from 'chai';
import { myFunction } from './myFunction';
describe('myFunction - basic functionality', () => {
it('returns error if two arguments are not entered', () => {
const expected = {
success: false,
errorMessage:
'Be sure to include 2 arguments. Both arguments must be strings.',
};
const actual = myFunction();
expect(actual).to.deep.equal(expected);
});
});
I am expecting that arguments.length would refer to the arguments I wrote in my test for myFunction, but when adding console.log(arguments) to myFunction, it seems to be referring to the arguments called by mocha/chai(?) when running the tests.
Additionally, if I throw the function itself in a console just to test it, it works properly, and if I log the arguments in that case, it returns however many arguments I provide when calling the function in the console.
So, how do I get my mocha/chai test to have arguments refer to the arguments of myFunction and not something else? Please and thank you!

How to call another function inside function in export default?

export default {
one: () => {
//some codes
},
two: () => {
//some codes
one(); // error
this.one(); // error
}
}
I have module like that, and I want to call function one() inside function two().
But I got error like this : TypeError: Cannot read property 'one' of undefined.
How can I fix it? I want to know the cause.
What about extracting them out into separate functions and then include them in the export?
const one = () => {
//some codes
};
const two = () => {
//some codes
one();
};
export default {
one,
two
}
You shouldn´t use arrows function if you want to give a new context to the this keyword.
Look this example, it uses an arrow function in the two method. It would return error since the this keyword is not related to the object, but mantains the context from the last function.
let obj = {
one: function() {
console.log("one");
},
two: () => { // Arrow function
this.one();
}
}
obj.two();
If you use a normal function, the this keyword would be related to the object:
let obj = {
one: function() {
console.log("one");
},
two: function() { // Normal function
this.one();
}
}
obj.two();
This is the main difference between arrow functions and normal functions

Loop through an object of functions & add a single, new method to each single function within the Object

I have an object of functions & I need to add a new, single method called log(it prints the method's name) to each function within the Object dynamically at runtime.
For instance, let's say this is my dynamic object of functions:
let actions = {
theBoringFunction() {
return 'function 1'
},
anotherBoringFunction() {
return 'function 2'
},
theMostBoringFunction() {
return 'function 3'
},
}
I can add a new function to the methods individually like so:
actions.anotherBoringFunction.log = function () {
return console.log(this.name)
}
actions.anotherBoringFunction.log() // logs anotherBoringFunction
It works like a charm, but I have many functions within the actions object & I need to add log() to all of them.
I have tried looping through the object & adding the method like so:
// won't work key is typeof String :(
for (let key in actions) {
key.log = function () {
return console.log(this.name)
}
}
Obviously, it didn't work cause key is a type of string so it cannot add a method to it. How could I accomplish what I'm looking for? I have been trying with proxies, but no luck so far either.
Edit Number 1:
I have added a reproducible, example here.
let actions = {
theBoringFunction() {
return 'function 1'
},
anotherBoringFunction() {
return 'function 2'
},
theMostBoringFunction() {
return 'function 3'
},
}
// won't work key is typeof String :(
/* for (let key in actions) {
key.log = function () {
return console.log(this.name)
}
} */
actions.anotherBoringFunction.log = function () {
return console.log(this.name)
}
actions.anotherBoringFunction.log() // logs anotherBoringFunction
for (let key in actions) {
actions[key].log = function () {
return console.log(this.name)
}
}

Using a function defined inside an exports function, from another file

I have some code like this in a file helperFunctions.js:
exports helperFunctions = () => {
const functionA = async(args) => {
console.log(args);
};
const functionB = async(args) => {
functionA(myArg);
};
}
How can I call functionA and functionB from a separate file altogether, say, main.js?
I've tried:
import { helperFunctions } from './helperFunctions';
//...some code
helperFunctions.functionA('hello');
// OR
functionA('hello');
The specific error is:
TypeError: _helperFunctions.helperFunctions.functionA is not a function
and when trying the second solution, it's:
ReferenceError: functionA is not defined
I'm trying to avoid importing literally every single function I'm using (by way of exporting every single function I'm using). I'd like to do something like helperFunctions.function for the functions I need.
It really need to be a function? You could export an Object:
// helperFunctions.js
let helperFunctions = {
functionA: async (args) => {
console.log(args);
},
functionB: async (args) => {
functionA(myArg);
}
}
exports helperFunctions;

Lodash's _.debounce() not working in Vue.js

I am trying to run a method called query() when a component property called q in Vue.js is modified.
This fails because this.query() is undefined. This is referring to my component's instance but somehow does not contain the methods.
Here's the relevant code part where I'm trying to watch the component property q and run the query() function:
methods: {
async query() {
const url = `https://example.com`;
const results = await axios({
url,
method: 'GET',
});
this.results = results.items;
},
debouncedQuery: _.debounce(() => { this.query(); }, 300),
},
watch: {
q() {
this.debouncedQuery();
},
},
Error:
TypeError: _this2.query is not a function
If I write the debounce() call as below, the TypeError: expected a function error appears even earlier, at the page load.
debouncedQuery: _.debounce(this.query, 300),
The issue comes from the lexical scope of the arrow function you define within _.debounce. this is bound to the object you are defining it in, not the instantiated Vue instance.
If you switch out your arrow function for a regular function the scope is bound correctly:
methods: {
// ...
debouncedQuery: _.debounce(function () { this.query(); }, 300)
}
We can do it by plain JS (ES6) with few lines of code:
function update() {
if(typeof window.LIT !== 'undefined') {
clearTimeout(window.LIT);
}
window.LIT = setTimeout(() => {
// do something...
}, 1000);
}
As answered in another post This is undefined in Vue, using debounce method the best way to add debouncing IMO is to create the method normally in methods as eg:
setHover() {
if (this.hoverStatus === 'entered') {
this.hoverStatus = 'active'
}
},
But then replace it in your created block eg:
created() {
this.setHover = debounce(this.setHover, 250)
},

Categories

Resources