I am trying to use the extends for array ..what should I put in the constructor..Here is the code
class List extends Array
constructor: ()->
super arguments
this
list = new List("hello","world")
alert list[0]
Doesn't seem to work..
There is no easy way to "inherit" from the array prototype. You should use composition , i.e.
class List
constructor: ()->
this.array = new Array(arguments);
getArray :()->
this.array
list = new List("hello","world")
alert list.getArray()[0]
or you will spend your time implemented complicated solutions that will fail as soon as you try to parse the array or access its length value.
more on the issue :
http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/
I haven't been using coffee script lately, so this is just a guess, but maybe something like:
class List extends [].prototype
might work?
EDIT: Per "mu is too short"'s comment, it seems the problem isn't coffee script related at all. You might find this related SO post useful, as the selected answer provides two possible solutions to this problem:
Is this a reasonable way to 'subclass' a javascript array?
Related
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.
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
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 have defined a get_queryset() method where i want to return two queryset objects like:
get_queryset(self):
r1 = Books.objects.filter(auther_id=1);
r2 = Books.objects.filter(~Q(auther_id=1));
return r1,r2
The call to this method comes from a javascript file with an ajax call.
Now i want to access r1 and r2 individually in the js file.
I tried doing
r=chain(r1,r2) // in views.py
r.r1.fieldName and r.r2.fieldName // in js file.
I am unsure how could i unchain the itertools object. If it is not possible can anyone tell me about some other approach for this.
I also see method like ifilter() and etc to access the object but i want to access it in js.
EDIT: I have edited the code . CAN i club both query like
Books.objects.all()
and in the js do something to get two lists one having books by auther_id 1 and second list having other auther ids.
This doesn't make any sense at all. You can't 'unchain' something; the whole point of chain is that it makes the individual elements into one single undifferentiated item, there is no way of telling where one of the originals ended and the next started.
If you want to access two querysets individually in the template, then pass two individual querysets.
I have
class A{
users = new B().users;
}
class B{
users : Array<any> = [];
}
at the first run the users fields are the same in both classes , but when users in class B changed the users in A isn't changed .
example : at first A.users and B.users are [user1]
when I add new user to B.users ([user1, user2]) A.users still the same .
Any idea ?
Thanks in advance ...
Any idea
Depends on how you add them. If you are doing something like b.users = b.users.concat([another]); then b.users will be a new array distict from the one that is referenced by A.
NOTE: Having two classes point the same array seems like a bad idea where mutation will quickly get out of hand and you will not know what moved your cheese. But there isn't more architecture advice I can give without a larger context that you can present in a separate question if you want.