I try to pass different amount of arguments in different cases.
I have the next code:
function getByteCode(tokenData, incomeData){
incomeData.volume = Number(incomeData.volume) * Math.pow(10,tokenData.decimals);
incomeData.volume = incomeData.volume.noExponents();
let web3 = new Web3();
let instanceContract = new web3.eth.Contract(abi);
instanceContract.options.address = tokenData.address;
let necessaryMethod = instanceContract.methods[incomeData.methodCall];
let methodCall = necessaryMethod(incomeData.destination_address, incomeData.volume);
return methodCall.encodeABI();
} catch (err) {
sails.log(err);
return {
state: 'fail',
message: 'There is error in creation byte code \n' + err
}
}
}
In necessaryMethod I want to pass two arguments in one case and pass three or more argument in other case. How can I do it? Maybe I should use "arguments", but I don`t understand how?
Ok, tank you for the helping. I have used method .apply()
let web3 = new Web3();
let instanceContract = new web3.eth.Contract(abi);
instanceContract.options.address = tokenData.address;
let necessaryMethod = instanceContract.methods[incomeData.methodCall];
let methodCall = necessaryMethod.apply(this, incomeData.argumentsForFunction);
return methodCall.encodeABI();
In first case I called function getByteCode(firstObj, incomeData) and there is next array in incomeData.argumentsForFunction = ['0x323.....', '1500000000'].
In other case I called function getByteCode(firstObj, incomeData) with incomeData.argumentsForFunction = ['0x323.....', '0x3228....', '54454000000']
Related
I have a function: I need to know from Wiktionary API if a user´s input german noun / adjective exists and its grammatical gender.
But the function always returns undefined although:
I asked for a return
the function is async
I used .onload on the function call waiting for the response
Could you please explain me what I am doing wrong? It´s the first time I work with APIs and I am pretty confused.
Thanks
check(userInput).onload;
async function check(word) {
$.getJSON('http://de.wiktionary.org/w/api.php?action=parse&format=json&prop=text|revid|displaytitle&callback=?&page=' + word,
function (json) {
try {
let variable = json.parse.text['*'];
let nounM = variable.search('id=\"Substantiv,_m\">');
let nounF = variable.search('id=\"Substantiv,_f\">');
let nounN = variable.search('id=\"Substantiv,_n\">');
let adjective = variable.search("href=\"#Adjektiv");
let gender = Math.max(nounM,nounF,nounN,adjective);
console.log(gender);
return gender;
} catch (e) {
console.log(e);
return undefined;
}
});
};
This question already has an answer here:
using variable results (contents) to create new variables
(1 answer)
Closed 10 months ago.
I have a list
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
how can I use these peoples numbers if their names matches another variable result?
We have
var name = *selected server-side student names*
and by these * signs I mean it's a great list that name gives up but it only gives up one name out of that list at the time we call it.
If one of these students is selected by name variable, how can I use the number defined in front of that name in const StudentCode to generate a url?
Suppose you get Rose! Then the number for Rose is: 35621548 and the url for example will be https://www.35621548.com. What code can we use to generate this url for example in console?
console.log(url)
Use this:
if (StudentCode.hasOwnProperty(name){
const url = `https://www.${StudentCode[name]}.com`
}
This function will return you the url on the basis of the student name that is passed in this function.
function returnURL(studentName){
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
if (!!!StudentCode[studentName]) return "";
return "https://" + StudentCode[studentName] + ".com";
}
console.log(returnURL("Rose"));
Hope, this helps!!
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
let studentName = "Jack"
const url = `https://${StudentCode[studentName]}.com`
console.log(url)
export const studentUrlModule = (function() {
const studentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const url = 'https://$code.com'
const generateUrl = function(code = '') {
if (!url) {
throw new Error('Url is not defined')
} else if (!code) {
throw new Error('Code is not defined')
};
return url.replace('$code', `${code}`);
}
function getCode(name = '') {
const code = studentCode[name];
if (!code) {
throw new Error(`There is no code with name(${name}).`);
}
return code;
}
function getUrl(name = '') {
if (!name) {
throw new Error('StudentName is undefined')
};
const code = getCode(name);
const studentUrl = generateUrl(code);
return studentUrl;
}
return {
generateUrl,
getCode,
getUrl,
};
}());
Maybe it helps. If the code was not founded then it throws an error. Please use try, catch error handlers to handle errors.
-- Update
I updated the code and as you can see it's a module and you need to import it everywhere you like to use this.
if you are not familiar with modules and how to use them inside the browser check documents.
Mozila documents
Super Simple Start to ESModules in the Browser
Hi i have a weird javascript issue.Here's my code I am not able to send these keys in my designOrder object. My Object does not have these fronImage and backImage keys that i am sending in my code.
let designOrder = await dbCall();
let allImages = []
allImageIds.push(designOrders.frontImageId);
allImageIds.push(designOrders.backImageId);
allImages = await dbCall();
let allImagesHash = {};
allImages.forEach(obj) => {
obj.image = JSON.parse(image)
allImagesHash[image.id] = image;
}
if(designOrder.backImageId){
designOrder.backImage = allImagesHash[designOrder.backImageId]
}
// if i do console.log("1", designOrder.backImage) it will log the designOrder.backImage
if(designOrder.frontImageId){
designOrder.frontImage = allImagesHash[designOrder.frontImageId]
}
// if i do console.log("2", designOrder.frontImage) it will log the designOrder.backImage
// but while console.log("3", designOrder) it will not show the backImage and frontImage keys
return designOrder;
It actually solved it after the first dbCall() i have added this line of code and it worked.
designOrder = designOrder.toJSON();
toJson function is defined within the mongoose schema.
I have the following code:
const readDataFromSql = () => {
// going to have to iterate through all known activities + load them here
let sql = "[...]"
return new Promise((resolve, reject) => {
executeSqlQuery(sql).then((dict) => {
let loadedData = [];
for (let key in dict) {
let newItemVal = new ItemVal("reading hw", 7121, progress.DONE);
loadedData.push(newItemVal);
}
resolve(loadedData);
});
});
}
ItemVal implementation:
class ItemVal {
constructor(name, time, type) {
this.name = name
this.time = time
this.type = type
}
}
Let's assume that newItemVal = "reading hwj", 5081, progress.PAUSED when readDataFromSql() first runs.
readDataFromSql() is then again called after some state changes -- where it repulls some information from a database and generates new values. What is perplexing, however, is that when it is called the second time, newItemVal still retains its old properties (attaching screenshot below).
Am I misusing the new keyword?
From what I can see in your example code, you are not mutating existing properties but creating a new object with the ItemVal constructor function and adding them to an array, that you then return as a resolved promise. Are you sure the examples you give a correct representation of what you are actually doing
Given that, I'm not sure what could be causing the issue you are having, but I would at least recommend a different structure for your code, using a simpler function for the itemVal.
Perhaps with this setup, you might get an error returned that might help you debug your issue.
const itemVal = (name, time, type) => ({ name, time, type })
const readDataFromSql = async () => {
try {
const sql = "[...]"
const dict = await executeSqlQuery(sql)
const loadedData = dict.map((key) =>
ItemVal("reading hw", 7121, progress.DONE)
)
return loadedData
} catch (error) {
return error
}
};
If the issue is not in the function, then I would assume that the way you handle the data, returned from the readDataFromSql function, is where the issue lies. You need to then share more details about your implementation.
const readDataFromSql = async () => {
let sql = "[...]"
------> await executeSqlQuery(sql).then((dict) => {
Use the await keyword instead of creating a new promise.
I did some modification and found that below code is working correctly, and updating the new values on each call.
const readDataFromSql = () => {
return new Promise((resolve, reject) => {
let loadedData = [];
let randomVal = Math.random();
let newItemVal = new ItemVal(randomVal*10, randomVal*100, randomVal*1000);
loadedData.push(newItemVal);
resolve(loadedData);
});
}
Could you recheck if you are using below line in the code, as it will instantiate object with same properties again and again.
let newItemVal = new ItemVal("reading hw", 7121, progress.DONE);
You can modify your code as below to simplify the problem.
const readDataFromSql = async () => {
// going to have to iterate through all known activities + load them here
let sql = "[...]" // define sql properly
let result = await executeSqlQuery(sql);
let loadedData = [];
for (let row in result) {
let newItemVal = new ItemVal(row.name, row.time, row.type);
loadedData.push(newItemVal);
}
return loadedData;
}
class ItemVal {
constructor(name, time, type) {
this.name = name
this.time = time
this.type = type
}
}
What you are talking about is an issue related to Object mutation in Redux, however, you didn't add any redux code. Anyway, you might be making some mistake while recreating(not mutating) the array.
General solution is the use spread operator as:
loadedData = [ ...loadedData.slice(0) , ...newloadedData]
In Dropdown.js line 188 instead of console.log-ing your variable write debugger;
This will function as a breakpoint. It will halt your code and you can inspect the value by hovering your mouse over the code BEFORE the newItemVal is changed again.
I can see in your screenshot that the newItemVal is modified again after you log it.
This is quite a frustrating issue I am stuck on. I am exporting a parent function with quite a rigid structure for the purpose of library mocking.
const responses = require("../responses/index.js");
function fetch (
first = "contactsMultiple",
second = "passwordFail",
third = "contactsMultiple") {
this.first = first;
this.second = second;
this.third = third;
this.iteration = 1;
this.fetch = () => {
let body;
switch (this.iteration) {
case 1 :
body = responses.contacts[this.first];
break;
case 2 :
body = responses.password[this.second];
break;
case 3 :
body = responses.contacts[this.third];
break;
default:
body = responses.contacts["contactsMultiple"];
break;
}
const response = {
status: 200,
statusText: "OK",
json: () => {
return body;
}
};
this.iteration++;
return response;
}}
module.exports = fetch;
I export this, then import it, create a new instance of the function so I can set properties that I wish to increment and also set via the construction of the function. But the code then expects a function called fetch.
I need to be able to call it like:
const Fetch = new fetch();
then pass Fetch into the existing classes.
If I log this new function I can see it has a fetch property of a type function. but I keep getting this.fetch is not a function.
What am I missing?
Many thanks