So I have an object build out that has a bunch of methods inside, I want to be able to narrow down some methods and see if there are other ways to do thing, so I will go into more description below:
So I have the following method which returns me a bunch of class names:
function class_names() {
return [
'optanon-category-C0001',
'optanon-category-C0002',
'optanon-category-C0003',
'optanon-category-C0004',
'optanon-category-C0005'
];
}
Now I have another method which basically outputs me a string based on the classname passed inside the parameter:
function classname_output(class_name) {
let output = '';
switch (class_name) {
case 'optanon-category-C0001':
output = 'Strictly Necessary Cookies';
break;
case 'optanon-category-C0002':
output = 'Performance Cookies';
break;
case 'optanon-category-C0003':
output = 'Functional Cookies';
break;
case 'optanon-category-C0004':
output = 'Targeting Cookies';
break;
case 'optanon-category-C0005':
output = 'Social Media Cookies';
break;
default:
output = 'No cookies match the specified class.';
break;
}
return output;
}
Is there a way that I can infuse the two methods into a single method with an object return and then target the object key?
You can have object (dictionary) that maps class names (key) to string (value), and then have a function to return the value if the key exists in the dictionary, or a default "Doesn't exist" string if it doesn't.
const dict = {
'optanon-category-C0001': 'Strictly Necessary Cookies',
'optanon-category-C0002': 'Performance Cookies',
'optanon-category-C0003': 'Functional Cookies',
'optanon-category-C0004': 'Targeting Cookies',
'optanon-category-C0005': 'Social Media Cookies'
};
function check(dict, className) {
return dict[className] ?? 'No cookies match the specified class.';
}
console.log(check(dict, 'optanon-category-C0003'));
console.log(check(dict, 'optanon-category-C0005'));
console.log(check(dict, 'optanon-category-C0000'));
Additional documentation
Nullish coalescing operator
Related
I'm working on a simple function that should return the quantity of specific elements in a passed range. I would like to use SWITCH statement but for some reason it doesn't work as I would expect:
function groupResult(range) {
const resultsQuantity = {
na: 0,
fail: 0,
pass: 0,
empty: 0
}
for(let i of range) {
switch(i){
case 'N/A':
resultsQuantity.na++;
break;
case "FAIL":
resultsQuantity.fail++;
break;
case "PASS":
resultsQuantity.pass++;
break;
default:
resultsQuantity.empty++
}
}
return resultsQuantity.na;
}
the function call in the spreadsheet looks like follows:
call of the function in the spreadsheet
but as result I get "0" instead of expected "2"
Use
for(let i of range.flat())
Because the range is a 2d array.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an array like the following:
[
'Main interaction point of this Map.',
'#param {*} Key',
'#param {*} Val',
'#returns {Map}'
]
I'd like to index it starting with a description tag, and then index the following parameters from #param, #returns, etc. The output should be something like this:
{
description: "Main iteration point of this Map.",
param: [
"{*} Key",
"{*} Val"
],
returns: "{Map}"
}
But, when I have leading no-tags, the last tag should apply:
[
'Sorts all the elements in the Map and returns it.',
'#param {Function} [cfn] Specifies a function that defines the sort order.',
'If omitted, the Collection is sorted according to each character\'s Unicode point value,',
'according to the string conversion of each element.',
'#param {*} [thisv] Value to use as `this` when executing functions.',
'#returns {Map}'
]
This should return:
{
description: "Sorts all the elements in the Map and returns it.",
param: [
"{Function} [cfn] Specifies a function that defines the sort order. If omitted, the Collection is sorted according to each character's Unicode point value, according to the string conversion of each element.",
"{*} [thisv] Value to use as `this` when executing functions."
],
returns: "{Map}"
}
Notice how the lines without a tag aren't a new param? I haven't figured out how to do this, could anybody give an example? Thanks
I'd suggest keeping a state/status variable keyword with the last tag seen, defaulting to "description". Then you would use recognizable tags like "#param" to update the status, and use the status to correctly write the rest of the line to your object.
// pseudocode
let output = {};
let keyword = "description";
for (const line of lines) {
// search for "#" at beginning, followed by a keyword, followed by a space and more content
const match = line.match(/^#(param|returns) (.*)$/);
let content;
if (match) {
keyword = match[1]; // "param" or "returns"
content = match[2]; // content is text following the tag
} else {
content = line; // content is the whole line
}
switch (keyword) {
// your logic
}
}
Maybe something like this?
const result = {
description: "",
param: [],
returns: ""
};
let last_tag = "";
for(text of test) {
switch(true) {
case text.startsWith("#param"):
last_tag = "#param";
result.param.push(text.replace("#param", "").trim());
break;
case text.startsWith("#returns"):
last_tag = "#returns";
result.returns += text.replace("#returns", "").trim();
break;
default:
switch(last_tag) {
case "#param":
result.param[result.param.length -1] += text;
break;
case "#returns":
result.returns += text;
break;
default:
result.description += text;
}
result.description = text;
}
}
I've been using the following command to test the function:
$hit sword 2 n
I've been playing around with console logs and logging wpn within the damage function returns sword. but when trying to call from the sword array by logging wpn[1] it returns "w". I feel like there's a simple solution that I'm just not seeing here.
const PREFIX ='$';
let args = message.content.substring(PREFIX.length).split(" "); //Reads discord comment with prefix $
let sword=[[4,6,6,6,6,8,10],["np"]];
let dam1=damage(args[2],args[1],args[3]);
message.channel.send("Your "+args[1]+" deals "+dam1+" damage.");
function damage(mod,wpn,armr){
let dam=Math.floor(Math.random() * 6) + +mod;
switch(wpn[1]){
case "pierce":
if (armr="y"){
dam+=1;
}
break;
case "np":
break;
}
if(dam<0){
dam=0;
} else if(dam>6){
dam=6;
};
return wpn[0][dam];
};
args[1] is the string "sword". That doesn't get replaced with the value of the sword variable.
If you want to use strings to access values, use an object to map them.
objects = {
"sword": [[4,6,6,6,6,8,10],["np"]],
...
};
let dam1=damage(args[2],objects[args[1]],args[3]);
I have two object JSON which having hierachical structure. I need to compare each object inside rowset in JSON. And where ever the value not gettng equal
then i have to addd one flag on corresponding object.
Please hava a look at my JSONs and give solution for that. If not angular atleast i have to achieve in Javascript.
Thanks in advance...
JSON1
{"entityinfo":{"entity":"Customer29Jan16","tenantid":"292FEC76-5F1C-486F-85A5-09D88096F098","timestamp":"2015-12-15T10:16:06.322Z"},"collections":{"Customer29Jan16":{"rowset":[{"CuId":"123","Name":"Ranjini","Quantity":"60","Rate":"60","Amount":"3600"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]},"Customer29Jan16Obj":{"rowset":[{"CuObjId":"456","FullAddress":"Electronic City","ObjAddr":"Bangalore","ObjName":"Testing"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]}}}
JSON2
{"entityinfo":{"entity":"Customer29Jan16","tenantid":"292FEC76-5F1C-486F-85A5-09D88096F098","timestamp":"2015-12-15T10:16:06.322Z"},"collections":{"Customer29Jan16":{"rowset":[{"CuId":"123","Name":"Vijay","Quantity":"60","Rate":"60","Amount":"3600"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]},"Customer29Jan16Obj":{"rowset":[{"CuObjId":"456","FullAddress":"SilkBoard","ObjAddr":"Bangalore","ObjName":"Testing"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]}}}
Use angular.equals(o1,o2) . It does deep comparison and does not depend on the order of the keys
angular.equals(JSON1, JSON2); // return boolean (true or false) based on the comparison
refer : Angularjs Docs
I've made an starting example for you to build on. You can play with it here.
JavaScript
var json1 = {"entityinfo":{"entity":"Customer29Jan16","tenantid":"292FEC76-5F1C-486F-85A5-09D88096F098","timestamp":"2015-12-15T10:16:06.322Z"},"collections":{"Customer29Jan16":{"rowset":[{"CuId":"123","Name":"Ranjini","Quantity":"60","Rate":"60","Amount":"3600"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]},"Customer29Jan16Obj":{"rowset":[{"CuObjId":"456","FullAddress":"Electronic City","ObjAddr":"Bangalore","ObjName":"Testing"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]}}};
var json2 = {"entityinfo":{"entity":"Customer29Jan16","tenantid":"292FEC76-5F1C-486F-85A5-09D88096F098","timestamp":"2015-12-15T10:16:06.322Z"},"collections":{"Customer29Jan16":{"rowset":[{"CuId":"123","Name":"Vijay","Quantity":"60","Rate":"60","Amount":"3600"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]},"Customer29Jan16Obj":{"rowset":[{"CuObjId":"456","FullAddress":"SilkBoard","ObjAddr":"Bangalore","ObjName":"Testing"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]}}};
function compareJSON(json1, json2) {
var objectsDiffering = [];
compareJSONRecursive(json1, json2, objectsDiffering);
return objectsDiffering;
}
function compareJSONRecursive(json1, json2, objectsDiffering) {
for(prop in json1) {
if(json2.hasOwnProperty(prop)) {
switch(typeof(json1[prop])) {
case "object":
compareJSONRecursive(json1[prop], json2[prop], objectsDiffering);
break;
default:
if(json1[prop] !== json2[prop]) {
objectsDiffering.push(json1);
}
break;
}
}
else {
objectsDiffering.push(json1);
break;
}
}
}
var differing = compareJSON(json1, json2);
console.log(JSON.stringify(differing));
//Logs: [{"CuId":"123","Name":"Ranjini","Quantity":"60","Rate":"60","Amount":"3600"},{"CuObjId":"456","FullAddress":"Electronic City","ObjAddr":"Bangalore","ObjName":"Testing"}]
I'm looking for the best solution here, i've got an idea but thinking it could be done prettier.
I'm making an simple weather application. And i'm using Yahoo Weather api were they have got codes for weather conditions.
Depending on the condition i'm giving a code. Now, there are 50 codes and i've categorised them into 5 categories. In my case ex. my categori Snow contains 15 of Yahoo's condition codes.
Well, if you got a better idea (which i bet there is) be free to suggest.
My thought is to return the matching value from a set of arrays, but not shure how to do it.
My code now looks like this:
function getCondition(code) {
var snow = [1, 2, 3],
sun = [4, 5, 6];
}
What i need is the variable name that contains the matching number of the code?
I've made a JS-Fiddle
http://jsfiddle.net/BH8r6/
The fastest lookup (translating a Yahoo code to your label) is to use the code as array key (if they are sequential).
var weather = [];
weather[0] = "no_weather";
weather[1] = "snow";
weather[2] = "snow";
weather[3] = "snow";
weather[4] = "sun";
weather[5] = "sun";
weather[6] = "sun";
function getCondition(code) {
return weather[code];
}
Why dont you try an associative array when your key is your variable name and your values is the corresponding code for the variable name, thus your code will be something like this:
var myCodeArray=[];
myCodeArray["snow"]=[1, 2, 3];
myCodeArray["sun"] = [4, 5, 6];
now your method getCondition will be
function getCondition(code)
{
for(var definedCodeName in myCodeArray)
{
if(myCodeArray.hasOwnProperty(definedCodeName))
{
var array=myCodeArray[definedCodeName ];
for(var i=0;i<array.length;i++)
{
if(array[i]==code){
return definedCodeName ;}
}
}
}
return "Not found";
}
Demo
Why to complicate everything?! Just use 'switch' :
function getCondition(code) {
switch( code ){
case 1:
case 2:
case 4:
case 6:
return "snow";
case 3:
case 8:
case 9:
return "sun";
case 5:
case 7:
case 10:
return "cloudy";
}
return "none";
}