I apologise in advance for what is probably a really obvious fix..
I'm trying to render the output from an mssql stored procedure (multiple recordsets) in nodejs using handlebars.
(Also NOT a JS coder, or a coder really)
Challenge 1:
The SP provides data in a column format, while the graph plugin requires an array for label,x,y..
I though I solved this with a custom class with 3 arrays..
class myClass{
#X = [];
#Y = [];
#Label = [];
get X { return #X; }
get Y { return #Y; }
get Label { return #Label; }
Add(x,y,label){
#X.push(x);
#Y.push(y);
#Label.push(label);
}
}
But I'm getting something weird (but probably obvious)..
The query returns data as expected and I can loop over it creating a new myClass for each recordset and then adding the values into the arrays, I can also access each property through console.log.
What I can't do is send the object as whole to console, it prints as {myClass {}}.
Challenge 2:
It won't render through handlebars
I suspect that 1 is causing the other, but simply don't know enough to stay for sure.
Any help gratefully received :)
Fixed it
DON'T USE PRIVATE PROPERTIES...
Neither Handlebars or console.log use the get() function, so if it's private they can't see it...
If you have a similar issue, I hope this helps.
Related
I just started learning Linked List for a technical interview, so this question might seem a little weird.
I was reading an introduction article about Linked List from freecodecamp, and this is what the article
In JavaScript, a linked list looks like this:
const list = {
head: {
value: 6
next: {
value: 10
next: {
value: 12
next: {
value: 3
next: null
}
}
}
}
}
};
My question is, is this a real Linked List? Say I get a question "Print out all the elements in the following linked list, and implement a Linked List yourself." Can I just use the above code? I do know how to use classes to implement a linked list, but I am just wondering if the above code counts as a linked List.
I am asking this question because I only know how to solve the array algorithm question so far.
Say I want to print out all the elements in the array. I will need three steps.
Create an array. // Nums = [1,2,3];
write a function to print it out. // function printNums(Nums){ for (...){console.log(Nums[i]}}
call the function. // printNums(Nums);
So now, I want to do a Linked List version of this. How should I do it?
New Update:
So this is my LinkedList version of printing out all the elements. As a comment mentioned, what I did in the code is in fact a linked list, but it's not called implementation. But what if I just want to test my function? Does the following code make sense to you guys?
My question is, is this a real Linked List?
Yes, it is. You have a collection of data elements, where each data element points to the next.
Say I get a question "Print out all the elements in the following linked list, and implement a Linked List yourself." Can I just use the above code?
When asked to print a specific linked list, we should assume that it is made clear what the exact interface is of that linked list (e.g. nodes are linked via a property called next, and their values are accessed via a property called value). In case of the example list, that is clear. So yes, you could use the piece of code you provided.
The question to implement a Linked List yourself, is a different one. Although it could be understood to define one particular list, that is not how most would interpret that question. It is more likely that this means you should implement a linked list interface: i.e. write code that not only provides easy ways to construct any linked list, but also for using it (find a value, insert a node, delete a node, move a node, ...)
I am just wondering if the above code counts as a linked List.
Yes, the object literal you provided is (one particular instance of) a linked list.
Say I want to print out all the elements in the array. I will need three steps.
Create an array. // Nums = [1,2,3];
Here you make use of a feature of the JavaScript language. Implicitly a constructor is behind this: new Array(1, 2, 3). This constructor is provided as part of the core language. You also get access to methods like push, pop, indexOf, slice, splice, ...etc. All out of the box.
The difference with linked lists is that core JavaScript does not offer an implementation for it. You have to throw your own. Sure, you can use an object literal to create one linked list, but it is quite a verbose way (imagine a list with 100 numbers), and error prone (what if you misspelled next somewhere half way?)
So now, I want to do a Linked List version of this. How should I do it?
If the purpose is only to print the content of a linked list, and nothing else, you can do it like you did. But to get something that offers an interface like you get out of the box for arrays, you would write a class with some useful methods, so you could write:
let myList = LinkedList.from(6, 10, 12, 3);
console.log(...myList.values()); // outputs 6 10 12 3
But what if I just want to test my function? Does the following code make sense to you guys?
Yes, that is fine. If you know that your print function will get either null or an object that has value and next properties, where the next property can be null or another such object, ... then it is fine. In other words: you need to know the interface.
var l = head;
while (l != null) {
console.log(l.value);
l = l.next;
}
Trick is to use while loop until next element is null.
let prev: LinkedListElement<T> | null = this._start;
let finalEl: LinkedListElement<T> = prev;
let counter = 0;
while (prev !== null) {
const retVal = callback(prev, counter);
if (!retVal) {
break;
}
finalEl = prev;
prev = prev.next;
counter++;
}
Let me know if this works.
Also look at this LinkedList class I have created, traverse function is matching the requirement you have.
Class GitHub
NPM package - #dsinjs/linked-list
Complete documentation
I have an objects containing property playerData which can look like this for example:
this.playerData = {"username1":{"hand":["AD,"JD","2D","3H"],"points":0}}
on a websocket event I'm running a function trying to slice the hand array like this.
GAMES_LIST[gameId] = associativ array where key is id and value is instance of object constructor.
handIndex is a number which is an integer.
socket.on('event',function(data){
GAMES_LIST[data.gameId].playerData[data.someUsername].hand.slice(data.handIndex,1);
});
The slice doesn't work and the array is unaffected. When I do it outside the function
like this it works.
var game = gameConstructor(some params...);
game.playerData[someUsername].hand.slice(handIndex,1);
Getting no errors. Gone through everything rigorously but can't seem to find the problem. Had to leave out a lot of code that would be to complicated to get a grasp of quickly but have simplified that which is relevant. Would greatly appreciate some help. Thanks in Advance.
To preface, I have found a solution that works for me in the situations I have tried it, but I am fairly new to javascript and RXJS and don't fully understand what the solution is doing so I can't be sure if it will work in every instance.
I am using reactive forms and have arrays of checkboxes, what I would like to do is get an array of all of the keys used to generate the checkboxes, but without any of the unchecked boxes. Ideally, I could use this to return additional values as well such as a user-readable string, but that is far from important as I can do that in a separate step fairly easily. I have come up with a few methods of my own, but they don't seem to be very robust or performant.
I would have replied on this thread, but I lack the reputation.
This is the best solution I have found, which I would be totally happy to use, but I don't have much experience with RXJS or maps in javascript so I am not totally sure what it is doing:
this.controlNames = Object.keys(this.checkboxGroup.controls).map(_=>_); //This seems to just produce an object of control keys as properties and their value
this.selectedNames = this.checkboxGroup.valueChanges.pipe(map(v => Object.keys(v).filter(k => v[k]))); //Some sort of magic happens and an array is generated and contains only the keys whose values are 'true'
I have tried breaking that snippet apart and using console.log to test what it is doing in each step, but it really didn't give me much useful information. Any advice or or better ideas would be thoroughly appreciated, there seem to be a lot of conventions in javascript that people adhere to and it can be hard to sort through what is a convention and what is actually doing something.
I think I found a way to break it down and get a grip on it and want to post my explanation for anyone who comes looking.
In this part, it is just creating an iterable map of the 'checkboxGroup.controls' object. This could have been used to loop over in the template and make all of the checkboxes. Since my form structure is already generated from arrays of objects with known properties, I don't need this. The underscores aren't doing anything special here, people just like to use them for private variables.
this.controlNames = Object.keys(this.checkboxGroup.controls).map(_=>_);
For those who are new to arrow functions or some of the conventions of javascript, the code above is not quite, but essentially shorthand for this:
this.controlNames = [];
Object.keys(this.checkboxGroup.controls).forEach(function(key) {
this.controlNames.push(key);
}
I have changed the short variables to longer ones to make them easier to understand in this second part. This maps the value changes observable as an iterable 'changesObj', retrieves the keys, and filters the keys by instances where the key has a true value. The code filter(key => changesObj[key]) returns the key if the key is not null, undefined, or false.
this.selectedNames = this.checkboxGroup.valueChanges.pipe(map(changesObj => Object.keys(changesObj).filter(key => changesObj[key])));
This is essentially just shorthand for this:
function propNotFalse (changes, prop) {
return changes[prop] == true;
}
this.selectedNames = this.alternateFilter = Object.keys(this.checkboxGroup.valueChanges).filter(this.propNotFalse.bind(null, this.checkboxGroup.valueChanges));
i am new to angular2 and when i was reviewing someone's code, one specific line got me confused
get formData() { return <FormArray>this.lienHolder.get('policyDetails'); }
why is the above line any different from this
formData() { return <FormArray>this.lienHolder.get('policyDetails'); }
I searched about this in google and found no actual results, can anyone help me to understand this.
UPDATE
what is the difference between this
var obj = { log: 0, get latest() { return this.log++; } };
and this
var obj = { log: 0, latest() { return this.log++; } };
both are giving me the updated value all the time i call them
obj.latest & obj.latest() -- returns updated result all the time then why use one over another?
get formData()
is called a getter accessor. It allows you get the property dynamically. It always should return a value.
https://www.typescriptlang.org/docs/handbook/classes.html
TypeScript supports getters/setters as a way of intercepting accesses
to a member of an object. This gives you a way of having finer-grained
control over how a member is accessed on each object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
Sometimes it is desirable to allow access to a property that returns a
dynamically computed value, or you may want to reflect the status of
an internal variable without requiring the use of explicit method
calls. In JavaScript, this can be accomplished with the use of a
getter.
In opposite to that, getFormDate() is a function, it can take arguments and not always returns values.
One of the cases, where I like to use a getter is when a property should be get from a service:
<p>{{dictionary.label1}}</p>
and then I get it from a service like this:
get dictionary(){
return this.myService.getDictionary();
}
this way when the service changed the data I dynamically can receive the value to my binding/model.
If I would have defined as the following:
dictionary: [];
ngOnInit(){
this.dictionary = this.myService.getDictionary();
}
then I would be 'stuck' with the old data while the service already received the new set of data. Of course, you can then set a change listener and trigger the update, but it's more code!
Think of getters as dynamic class properties.
UPDATE:
For the examples in your updated post, it's true, they give the same result, and it's a good thing! You can use both, but as they don't work similarly, you can have more options in some cases. It's not like only one or only the other, or which one is the best. In most of cases you can use both, it's where and for what you need to use them. Most of the times, it's a method which is used, as it has more comprehensive use: we use methods with or without parameters, to trigger actions on objects. But in some cases, again, it will not have the same flexibility as a getter. If you are hesitant which one to use, use the method first and when you see its limits, think if the getter would help you, as now you know what's its purpose, which is - a property, but dynamic!
An other example:
isShown:boolean; //is 'static', will return the same value unless you change it in some kind of a method
get isShown(){
return this.someCondition && this.someMethodResult() || this.anotherCondition
}
If someCondition and anotherCondition change and the result from someMethodResult had to come changed you don't have to request isShown value, it's done dynamically.
Opposite of that, you can have
setShown(){ //the method
this.isShow = !this.isShown;
}
Here setShown needs to be called so isShown could be updated.
Also, a getter can easily replace a method which only job is to return a class property value.
UPDATE2:
An other 'good' example for get. A case when a component needs to check if the user is logged to show/hide some buttons. Instead of subscribing to changes, you do:
HTML:
<button [hidden]="!isLogged">Log out</button>
Typescript:
get isLoggedIn(){
return this.authService.isLoggedIn();
}
And that's it! If the user is logged out the button will be disabled 'immediatly'. No nead for the heavy subscribe/unsubscribe...
with the get you can treat it like a var:
let something = formData;
otherwise you must invoke the function:
let something = formData();
You would use a get usually to format data as you retrieve it. for example:
let _number = '12';
get number(){
return parseInt(_number);
}
I am a little confused by the functionality of ImmutableJS when working with an array of objects. The following example shows that even though the List x is immutable, I can still modify properties of objects inside the list both with and without using Immutable List's update() function.
My question is, why would I use Immutable if I can still modify the contents of my objects? I expected this module to protect me from that. I realize that I will not be able to add or remove entire objects to/from the list, but that doesn't fully protect me from modifying the list, which when working with a list in React state, I do not want to be able to do.
The other interesting thing I noticed is that when I directly modify the name after first performing the update, x.get(0).name and y.get(0).name are both changed. I thought that the resulting list from update() would not contain references to the same objects in the list.
How and why is ImmutableJS really helping me in this case?
var x = Immutable.List.of({name: 'foo'});
console.log(x.get(0).name);
var y = x.update(0, (element) => {
element.name = 'bar';
return element;
});
console.log(x.get(0).name);
console.log(y.get(0).name);
x.get(0).name = 'baz';
console.log(x.get(0).name);
console.log(y.get(0).name);
Output:
foo
bar
bar
baz
baz
https://jsfiddle.net/shotolab/rwh116uw/1/
Example of #SpiderPig's suggestion of using Map:
var x = Immutable.List.of(new Immutable.Map({name: 'foo'}));
console.log(x.get(0).get('name'));
var y = x.update(0, (element) => {
return element.set('name', 'bar');
});
console.log(x.get(0).get('name'));
console.log(y.get(0).get('name'));
Output:
foo
foo
bar
While the last example shows what I was trying to accomplish, ultimately I don't know if I will end up using Map or List or even ImmutableJS at all. What I don't like is the alternate APIs (especially for a mapped object). I am afraid that when I hand my project off to another developer, or as others join the team, using these immutable objects and lists correctly will completely fall apart without the proper governance.
Maybe this is more of a commentary on React, but if React intends for the state to be immutable, but it's not enforced, it just seems to me like this will end up a mess in a project that is moving quickly with multiple developers. I was trying my best not to mutate the state, but forgetting that modifying an object in a list/array is very easy mistake to make.
The immutable.js does not provide true immutability in the sense that you could not modify the Objects directly - it just provides API which helps you to maintain the immutable state.
The update -function should return completely new version of the indexed object:
var y = x.update(0, (element) => {
return { name : "bar"};
});
But doing something like this is a big no-no: x.get(0).name = 'baz';
Here is a much better explanation of the whole thing than I could ever write:
https://github.com/facebook/immutable-js/issues/481
The point of immutable.js is to allow re-use of objects which are not modified, which consumes less memory and gives a good practical performance.
There is also library "Seamless immutable", which freezes the objects, so that they can not be modified, but this comes with some performance penalty under JavaScript: https://github.com/rtfeldman/seamless-immutable