I'm doing some exercises from school where is asking me to eval the class creation, I am given the html with several eval scripts. I'm supposed to create the javascript file to generate certain output.
This is the eval one:
try {
var output = eval('peter = new Person("Roger Roger")');
}
catch (err) {
var output = "[JavaScript Error] " + err.message;
}
if (output != '[Person "Roger Roger"]') {
error = true;
}
the expected output should be:
[Person "Roger Roger"]
but I'm getting
[object Object]
I've been looking around, but there isn't much information on how to evaluate the class creation.
Your help is very much appreciated.
When you coerce eval's return value to a string you get the default toString implementation.
You need to create a Person.prototype.toString method so coercion returns the output you're looking for, e.g.,
Person.prototype.toString = function() {
return "[Person " + this.name + "]";
}
var output = "" + eval('peter = new Person("Roger Roger")');
console.log(output);
> [Person Roger Roger]
OTOH, it's not super-clear to me what the assignment ultimately is.
Related
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]);
Hey there I am searching for a function which is printing a dynamic variable as completely as possible to the console in Dart language.
In PHP for instance I would use var_dump() in order to get all information about a variable.
In JavaScript I would do one of the following:
1) Convert Object to JSON and print console.log(JSON.stringify(obj))
2) Or a custom function like this:
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
However in Dart if I do print(variable) I get something like Instance of 'FooBarObject'. I cannot just convert an object to JSON like in JavaScript as this is not possible for all objects.
So my question in detail:
Is where a function or custom function in dart which can print a variable with unknown type (object, array, etc.) including all (public) properties as well as nested objects and variables to my console? Or which function is closest to this desire?
dart:developer library includes inspect function that allows debuggers to open an inspector on the object.
To use it add:
import 'dart:developer';
And then you can see your inspected variable/object in console with:
inspect(myVar);
There is no built in function that generates such an output.
print(variable) prints variable.toString() and Instance of 'FooBarObject' is the default implementation. You can override it in custom classes and print something different.
You can use reflection (https://www.dartlang.org/articles/libraries/reflection-with-mirrors) to build a function yourself that investigates all kinds of properties of an instance and prints it the way you want.
There is almost no limitation of what you can do and for debugging purposes it's definitely a fine option.
For production web application it should be avoided because it limits tree-shaking seriously and will cause the build output size to increase notable.
Flutter (mobile) doesn't support reflection at all.
You can also use one of the JSON serialization packages, that make it easy to add serialization to custom classes and then print the serialized value.
For example
https://pub.dartlang.org/packages/dson
I think there are others, but I don't know about (dis)advantages, because I usually roll my own using https://pub.dartlang.org/packages/source_gen
If it's a map then you can convert to JSON. First import convert package from flutter.
import 'dart:convert';
then convert to JSON and print
print(json.encode(yourMapVariable));
Update
Above answer is for map. For class / object add to toString() method.
Eg: say we have a user class
class User {
String name;
String address;
toString() {
return "name: " + name + ", address: " + address;
}
}
You can auto generate this toString() method using your IDE.
Simple little trick does the job
void printObject(Object object) {
// Encode your object and then decode your object to Map variable
Map jsonMapped = json.decode(json.encode(object));
// Using JsonEncoder for spacing
JsonEncoder encoder = new JsonEncoder.withIndent(' ');
// encode it to string
String prettyPrint = encoder.convert(jsonMapped);
// print or debugPrint your object
debugPrint(prettyPrint);
}
// To use simply pass your object to it
printObject(yourObject);
Instance of 'FooBarObject' This happens when you try to directly do print(object);
Even if you use convert package from flutter, it would throw Uncaught Error: Converting object to an encodable object failed:
To resolve this issue, first, make sure your model class or data class contains fromJson and toJson methods.
If you do so, your model class would look like this.
class User {
String name;
String gender;
int age;
User({this.name, this.gender, this.age});
User.fromJson(Map<String, dynamic> json) {
name = json['name'];
gender = json['gender'];
age = json['age'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['gender'] = this.gender;
data['age'] = this.age;
return data;
}
}
And to print this as json import convert package
import 'dart:convert';
And call json.encode
//after initializing the user object
print('value is--> ' + json.encode(user);
Which will print the data as
value is--> {"name": "Vignesh","gender": "Male","age": 25}
use await keyword with an object in async function
void _registerUser() async { print(await form.result); }
If you want to know more about an instance of any class in an android studio click on a class name before variable then press ctrl+b it will take you to the class file where this object belongs from there you can see user attributes and methods of this class.
Try this one..
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}
In Spring MVC and Jackson I have a really big Java object that I parse to a JSON string myBigJSONString (~1MB) and inline it into my HTML.
Then in my Javascript I do a JSON.parse(myBigJSONString) and everything works dandy.
However if I were to inline an syntactically correct Javascript object into my HTML and not a string representation thereof, my Javascript wouldn't have to read this huge string and parse it. It would already be parsed.
Question: How do I create a Javascript object from my Java object and inline it directly without going through a JSON string?
EDIT:
This is how my finished HTML looks right now:
var staticDataString = '[{\"propertyA\":\"valueA\"}, {\"propertyB\":\"valueB\"}]';
var staticData = JSON.parse(staticDataString);
This is how i want it to look
var staticData = [{propertyA:"valueA"}, {propertyB:"valueB"}];
In all current browsers this should work:
<script>
var obj = <c:out value="${$myserlvetmapping.myjson}"></c:out>;
alert(obj.test);
</script>
Whearat this is the Spring-Handler:
model.addAttribute("myjson","{test:2}");
Finally this would be the browsers sourcecode:
var obj = {test:2};
alert(obj.test);
And the alert reports 2.
About the creation of the JSON i suggest to use the "adapter-pattern", this means a lot of hand-written-code.
Why do you need the hand-written-adapter? Assuming you have crosswise referenced objects in java like This:
class Man {
Wife wife;
}
class Wife {
Man man;
}
Man joe = new Man();
Wife ann = new Wife();
joe.wife = ann;
ann.man = joe;
Your json would be
{man:{
name:'joe',
wife: {
name: 'ann',
man: {
name: 'joe',
wife: {
name: 'ann',
man: {
name: 'joe',
wife: {
.....
}
}
}
}
}
}}
To prevent recursion you can only use the Adapter-Pattern. This would work:
public final class ManJSONAdapter {
private final Man man;
public ManJSONAdapter(Man man){
this.man = man;
}
public String toJSON(){
String result="{";
if (man != null) {
result += "name:";
if (man.name == null){
result += "undefined"
} else {
result += "'" + StringEscapeUtils.ESCAPE_ECMASCRIPT.translate(man.name) +"'";
}
result += ",wife:";
if (man.wife == null) {
result += "undefined";
} else {
...
}
}
result += "}";
return result;
}
}
I'm writing a program (in JavaScript) that will determine the most suitable car based on a user's needs. I have 4 objects, each one a different car. For simplification purposes I will provide one object as an example. Assume there are 3 other objects with the same properties in my code (Fiat, Audi, BMW, etc.).
var chevy = {
make: "Chevy",
model: "Bel Air",
year: 1957,
color: "red",
passengers: 2,
convertible: false,
mileage: 1021
};
The goal is to pass each object as an argument to a function, and return a boolean value based on conditionals. Here is the function:
function prequal(car) {
if (car.mileage > 10000) {
return false;
}
else if (car.year > 1960) {
return false;
}
else {
return true;
}
}
And calling the function:
var worthALook = prequal(taxi);
if (worthALook) {
console.log("You gotta check out this " + taxi.make + " " + taxi.model);
}
else {
console.log("You should really pass on the " + taxi.make + " " + taxi.model);
}
Do I have to call each object seperately? Or is there a simplified way of calling the function for all 4 objects at once? I'm new to this and working through this problem spiked my curiosity.
Thanks!!
EDIT: Sorry for the rambling but I seem to have figured out a solution. I am getting the desired output by using a nested function:
function worthALook(car) {
var shouldYouBuy = prequal(car);
if (shouldYouBuy) {
console.log("You gotta check out this " + car.model);
}
else {
console.log("You should really pass on this " + car.model);
}
}
calling the original 'prequal' function (see above) inside the 'worthALook' function outputs:
You should really pass on this Taxi
You should really pass on this Cadillac
You gotta check out this Bel Air
You should really pass on this 500
After each object I called the worthALook function like so:
worthALook(chevy);
worthALook(fiat);
etc.
I received my desired output but does my code seem like overkill?
Thanks!
You could put the objects in an Array and filter what's worth a look. Return that object instead of a boolean.
function worthALook(){
return ([].filter.call(arguments, prequal) || [false])[0];
/* remove [0] from the above line and change [false] to false if you
want to return multiple cars that satisfy a condition. Use indexes if you do that */
}
var car = worthALook(chevy, fiat, audi, bmw); // pass inas many as you want
if(car) // check if it's a car
console.log("You gotta check out this " + taxi.make + " " + taxi.model);
The return statement is used with || so even if none of the cars satisfy the condition, then you could return false. Also, we are using arguments object, so you can pass in as many car objects to the worthALook function, which will make use of prequal function to filter 'em.
I have the following JSON response from a ajax-request.
var json = {
"response": {
"freeOfChargeProduct": {
"description": "Product",
"orderQty": 5,
"productName": "XYZ",
"qty": 6,
"details": {
"price": 55.5,
"instock": "true",
"focQuantity": 1
}
},
"orderLineId": 4788,
"totalOrderLinePrice": "741.36",
"totalOrderPrice": "1,314.92",
"totalQty": 17
};
The JSON dosen't always return a "freeOfChargeProduct" property. So if I want to get the "freeOfChargeProduct" price, then I have to do the following:
var getFreeOfChargeProductPrice = function() {
var r = json.response;
if (r && r.freeOfChargeProduct && r.freeOfChargeProduct.details) {
return r.freeOfChargeProduct.details.price;
}
return null;
};
No problems. But it's very annoying to check every property in the object, so I created a function that check if a property in a object is defined.
var getValue = function (str, context) {
var scope = context || window,
properties = str.split('.'), i;
for(i = 0; i < properties.length; i++) {
if (!scope[properties[i]]) {
return null;
}
scope = scope[properties[i]];
}
return scope;
};
var price = getValue('json.response.freeOfChargeProduct.details.price');
// Price is null if no such object exists.
Now to my question: Is this a good or bad way to check if a property exists in an object? Any better suggestions/methods?
EDIT:
I don't wan't to use the &&-operator. I am lazy and I'm looking for a reusable method to check if a object (or property of a object) is defined.
:) Thanks!
Use the guard pattern:
if (json.response && json.response.freeOfChargeProduct && json.response.freeOfChargeProduct.details) {
// you can safely access the price
}
This is how the guard pattern works.
if (a && a.b && a.b.c) { ... } else { ... }
The first check is "Does the property a exist?". If not, the else-branch gets executed. If yes, then the next check occurs, which is "Does object a contain the property b?". If no, the else-branch executes. If yes, the final check occurs: "Does the object a.b contain the property c?". If no, the else-branch executes. If yes (and only then), the if-branch executes.
Update: Why is it called "guard pattern"?
var value = a && b;
In this example, the member b (the right operand) is guarded by the && operator. Only if the member a (the left operand) is truthy ("worthy"), only then the member b is returned. If, however, the member a is falsy ("not worthy"), then it itself is returned.
BTW, members are falsy if they return these values: null, undefined, 0, "", false, NaN. Members are truthy in all other cases.
if(x && typeof x.y != 'undefined') {
...
}
// or better
function isDefined(x) {
var undefined;
return x !== undefined;
}
if(x && isDefined(x.y)) {
...
}
This will work for any data type in JavaScript, even a number that is zero. If you are checking for an object or string, just use x && x.y within the if statement, or if you already know that x is an object, if(x.y) ...
You could do something like this:
try{
var focp = json.response.freeOfChargeProduct
var text = "You get " + focp.qty + " of " +
focp.productName +
" for only $" + (focp.qty-focp.details.focQuantity)*focp.details.price +
", You save $" + focp.details.focQuantity*focp.details.price;
$("order_info").innerText = text;
} catch(e) {
// woops, handle error...
}
It would generate a message like this from the provided data in your question if the fields exists:
You get 6 of XYZ for only $277,5, You save $55.5
If the data is non-existing, you'll end up in the catch block. You could always just to a Try, Catch, Forget here if you can't come up with a way to handle the error (Maybe do a new AJAX request for the data?).
This is not a syntax issue as it is a design pattern issue.
Question A.
* Do you have control of the json server?
If the answer to this is no, which I assume, the situation will be all on the client.
Please read this:
http://martinfowler.com/eaaDev/PresentationModel.html
As the server is the source, in this case it will provide the model.
This pattern specifies an additional artifact: The presentation model (PM). In javascript i would suggest two artifacts, a additional for the convertor code.
According to this design pattern the PM is responsible for converting the model to the PM, and back again if necessary. In your case no conversion from PM to M will ever occur.
This means that a js object has a method or constructor that digest the model and translate itself, with the help of the convertor (below).
Doing this you will end up with a PM looking like this:
var OrderlinePM = {
"hasFreeOfCharge": false | true,
"freeOfCharge" : {...}
`enter code here`
this.getFreeOfCharge = function() {
...
}
this.fromModel = function(jsonEntry, convertor) {
//convert this with the convertor ;) to a for this specific view usable OrderlinePM
// also inwith
...
}
enter code here
"orderLineId":0,
"totalOrderLinePrice":"741.36",
"totalOrderPrice":"1,314.92",
"totalQty":17
};
function mySpecialFunctionPMConvertor {
this.fromModel = function() {
... //do strange stuff with the model and poulate a PM with it.
}
}
Ok, I give up trying to format code in this rich text editor :(
You can have several PM:s for diffrent tasks all depending on the same model object.
In addition this will make the converter object testable in something that could be automatically executed.... err ok maby manually, but anyway.
So the problem of the cumbersome reflection code is really not a problem. But cohesion is a issue, expessially in JavaScript.