I wonder if there is an equivalent of c/++ union in Javascript? I need to use it as a library I use for an Html5 game wants some fixed variable names for the object I pass to a function of this library however it is much easier for me to keep the data in an array for easier calculation.
To give an example, say there is a function 'F' in the library which takes a transformation matrix as a parameter. The parameter must have variable names 'a', 'b', ... 'f' which correspond to matrix elements(m[0][0], m[0][1] ...) consecutively. I have my own matrix class for calculations in which I use an array.
I know that entering the parameter 'on the fly', as shown below, sorts out my problem however I don't want to do that every time I call the function nor I want to write a proxy function.
F({a:m[0][0], b:m[0][1], c:[0][2], d:m[1][0], e:m[1][1], f:[1][2]});
is there any way around that such as union?
No, there's not.
There is no concept of a union, but since the language is loosely-typed you should never need anything of the sort.
You can change the type that is in a variable on the fly (and of course you can use an object with properties which are also loosely typed).
Related
I am currently in the process of writing a GUI which fundamentally allows users to edit/populate/delete a number of settings files, where the settings are stored in JSON, using AJAX.
I have limited experience with JavaScript (I have little experience with anything beyond MATLAB to be frank), however I find myself restructuring my settings structure because of the semantics of working with an object containing more objects, rather than an array of objects. In C# I would do this using a KeyValuePair, however the JSON structure prevents me from doing what I'd really like to do here, and I was wondering whether there was an accepted convention for do this in JavaScript which I should adopt now, rather than making these changes and finding that I cause more issues than I solve.
The sample data structure, which has similar requirements to many of my structures, accepts any number of years, and within these any number of events, and within these a set number of values.
Here is the previous structure:
{"2013":
{
"someEventName":
{
"data1":"foo",
"data2":"bar",
...},
...},
...}
Here is my ideal structure, where the year/event name operates as a key of type string for a value of type Array:
["2013":
[
"someEventName":
{
"data1":"foo",
"data2":"bar",
...},
...],
...]
As far as I am aware, this would be invalid JSON notation, so here is my proposed structure:
[{"Key":"2013",
"Value":
[{"Key":"someEventName",
"Value":
{
"data1":"foo",
"data2":"bar",
...}
},
...]
},
...]
My proposed "test" for whether something should be an object containing objects or an array of objects is "does my sub-structure take a fixed, known number of objects?" If yes, design as object containing objects; if no, design as array of objects.
I am required to filter through this structure frequently to find data/values, and I don't envisage ever exploiting the index functionality that using an array brings, however pushing and removing data from an array is much more flexible than to an object and it feels like using an object containing objects deviates from the class model of OOP; on the other hand, the methods for finding my data by "Key" all seem simpler if it is an object containing objects, and I don't envisage myself using Prototype methods on these objects anyway so who cares about breaking OOP.
Response 1
In the previous structure to add a year, for example, the code would be OBJ["2014"]={}; in the new structure it would be OBJ.push({"Key":"2014", "Value":{}}); both of these solutions are similarly lacking in their complexity.
Deleting is similarly trivial in both cases.
However, if I want to manipulate the value of an event, say, using a function, if I pass a pointer to that object to the function and try to superceed the whole object in the reference, it won't work: I am forced to copy the original event (using jQuery or worse) and reinsert it at the parent level. With a "Value" attribute, I can overwrite the whole value element however I like, provided I pass the entire {"Key":"", "Value":""} object to the function. It's an awful lot cleaner in this situation for me to use the array of objects method.
I am also basing this change to arrays on the wealth of other responses on stackoverflow which encourage the use of them instead of objects.
If all you're going to do is iterate over your objects, then an array of objects makes more sense. If these are settings and people are going to need to look up a specific one then the original object notation is better. the original allows people write code like
var foo = settings['2013'][someEventName].data1
whereas getting that data out of the array of objects would requires iterating through them to find the one with the key: 2013 which depending on the length of the list will cause performance issues.
Pushing new data to the object is as simple as
settings['2014'] = {...}
and deleting data from an object is also simple
delete settings['2014']
Given two Javascript objects (A and B), is there a way to generate the JSON patch, so that when that patch is applied to A it would change the object's properties to that of object B?
For example, given hypothetical JSONPatch function (perhaps being a function of similar name to one of those linked below), what is desired is the generate_patch function.
patch = generate_patch(A, B)
JSONPatch.apply(patch, A) # modifies A so that it has the same properties as B.
In this question A and B are Javascript objects. A patch created by RFC6902 is JSON that would indicate an array of operations which when applied to A that object would become B. The generate_patch function need not return JSON though, rather for efficiency could return a Javascript object that becomes the RFC6902 JSON-patch document when JSON.stringify is called on it.
The projects I have found on the topic are:
https://github.com/bruth/jsonpatch-js - only patches (does not generate a patch)
http://jsonpatchjs.com/ - same
https://github.com/Starcounter-Jack/Fast-JSON-Patch - observes an object, does not take two different objects
Turning my comment into an answer...
This code https://www.npmjs.org/package/rfc6902 seems to be a full javascript implementation of both patch and diff for the stated RFC.
I haven't used it myself, but the documentation makes it look like what you asked for.
Since version 0.3.9, https://github.com/Starcounter-Jack/Fast-JSON-Patch has a compare method which returns a difference between 2 objects. If I understand correctly, that may be what you were looking for
I have also written a library to generate patches: https://github.com/gregsexton/json-patch-gen
I found out about 'rfc6902' after having written and used json-patch-gen. I'm not sure how they compare: it may be worth trying out both to see if one fits your needs better.
I'm making a jquery plugin to show piano scales.
I have a function called markScale(a, b) which will be used to highlight certain scales (the a parameter gives the pitch of the starting note, ie. how many semitones up from C, the default scale). That's no problem.
The problem comes with b, the type of scale or chord to display. I have defined which keys to use in the different types of scale as follows:
var majorScale=[12,14,16,17,19,21,23,24];
var nminorScale=[12,14,15,17,19,20,22,24];
var hminorScale=[12,14,15,17,19,20,23,24];
And so what I'm looking to do is the following:
for(i=0;i<8;i++){
$('#key-'+(b[i]+a)+'-marker').show();
}
markScale(0,"majorScale") doesn't work, because that's just a string and doesn't refer to the array variable that I need.
How do I refer to the array variable as a parameter of the function?
Thanks
I think we're missing a little info, but if you want to asccess the scale by name, put the arrays in an object instead of individual variables.
var scales = {
majorScale:[12,14,16,17,19,21,23,24],
nminorScale:[12,14,15,17,19,20,22,24],
hminorScale:[12,14,15,17,19,20,23,24]
};
Then you can reference the scales using a string...
var the_scale = "majorScale"
scales[the_scale][i];
While it is possible to refer to local variables from a string, it requires an approach that is generally not recommended. Global variables are a little easier.
If you were trying to pass the scale, then you don't use a string at all. You just use a direct reference. majorScale
Its hard to tell without more context, but have you tried passing the array majorScale itself to the markScale() function?
as in:
markScale(c, majorScale);
instead of a string:
markScale(c, "majorScale");
After some time programming in Javascript I have grown a little fond of the duality there between objects and associative arrays (dictionaries):
//Javascript
var stuff = { a: 17, b: 42 };
stuff.a; //direct access (good sugar for basic use)
stuff['a']; //key based access (good for flexibility and for foreach loops)
In python there are basically two ways to do this kind of thing (as far as I know)
Dictionaries:
stuff = { 'a': 17, 'b':42 };
# no direct access :(
stuff['a'] #key based access
or Objects:
#use a dummy class since instantiating object does not let me set things
class O(object):
pass
stuff = O()
stuff.a = 17
stuff.a = 42
stuff.a #direct access :)
getattr(stuff, 'a') #key based access
edit: Some responses also mention namedtuples as a buitin way to create lighweight classes for immutable objects.
So my questions are:
Are there any established best-practices regarding whether I should use dicts or objects for storing simple, method-less key-value pairs?
I can imagine there are many ways to create little helper classes to make the object approach less ugly (for example, something that receives a dict on the constructor and then overrides __getattribute__). Is it a good idea or am I over-thinking it?
If this is a good thing to do, what would be the nicest approach? Also, would there be any good Python projects using said approach that I might take inspiration from?
Not sure about "established best practices", but what I do is:
If the value types are homogenous – i.e. all values in the mappings are numbers, use a dict.
If the values are heterogenous, and if the mapping always has a given more or less constant set of keys, use an object. (Preferrably use an actual class, since this smells a lot like a data type.)
If the values are heterogenous, but the keys in the mapping change, flip a coin. I'm not sure how often this pattern comes up with Python, dictionaries like this notably appear in Javascript to "fake" functions with keyword arguments. Python already has those, and **kwargs is a dict, so I'd go with dicts.
Or to put it another way, represent instances of data types with objects. Represent ad-hoc or temporary mappings with dicts. Swallow having to use the ['key'] syntax – making Python feel like Javascript just feels forced to me.
This would be how I decide between a dict and an object for storing simple, method-less key-value pairs:
Do I need to iterate over my key-value pairs?
Yes: use a dict
No: go to 2.
How many keys am I going to have?
A lot: use a dict
A few: go to 3.
Are the key names important?
No: use a dict
Yes: go to 4.
Do I wish to set in stone once and forever this important key names?
No: use a dict
Yes: use an object
It may also be interesting to tale a look at the difference shown by dis:
>>> def dictf(d):
... d['apple'] = 'red'
... return d['apple']
...
>>> def objf(ob):
... ob.apple = 'red'
... return ob.apple
...
>>> dis.dis(dictf)
2 0 LOAD_CONST 1 ('red')
3 LOAD_FAST 0 (d)
6 LOAD_CONST 2 ('apple')
9 STORE_SUBSCR
3 10 LOAD_FAST 0 (d)
13 LOAD_CONST 2 ('apple')
16 BINARY_SUBSCR
17 RETURN_VALUE
>>> dis.dis(objf)
2 0 LOAD_CONST 1 ('red')
3 LOAD_FAST 0 (ob)
6 STORE_ATTR 0 (apple)
3 9 LOAD_FAST 0 (ob)
12 LOAD_ATTR 0 (apple)
15 RETURN_VALUE
Well, if the keys are known ahead of time (or actually, even not, really), you can use named tuples, which are basically easily-created objects with whatever fields you choose. The main constraint is that you have to know all of the keys at the time you create the tuple class, and they are immutable (but you can get an updated copy).
http://docs.python.org/library/collections.html#collections.namedtuple
In addition, you could almost certainly create a class that allows you to create properties dynamically.
Well, the two approaches are closely related! When you do
stuff.a
you're really accessing
stulff.__dict__['a']
Similarly, you can subclass dict to make __getattr__ return the same as __getitem__ and so stuff.a will also work for your dict subclass.
The object approach is often convenient and useful when you know that the keys in your mapping will all be simple strings that are valid Python identifiers. If you have more complex keys, then you need a "real" mapping.
You should of course also use objects when you need more than a simple mapping. This "more" would normally be extra state or extra computations on the returned values.
You should also consider how others will use your stuff objects. If they know it's a simple dict, then they also know that they can call stuff.update(other_stuff) etc. That's not so clear if you give them back an object. Basically: if you think they need to manipulate the keys and values of your stuff like a normal dict, then you should probably make it a dict.
As for the most "pythonic" way to do this, then I can only say that I've seen libraries use both approaches:
The BeautifulSoup library parses HTML and hands you back some very dynamic objects where both attribute and item access have special meanings.
They could have chosen to give back dict objects instead, but there there is a lot of extra state associated with each object and so it makes perfect sense to use a real class.
There are of course also lots of libraries that simply give back normal dict objects — they are the bread and butter of many Python programs.
By this I mean when calling .push() on an Array object and JavaScript increases the capacity (in number of elements) of the underlying "array". Also, if there is a good resource for finding this sort of information for JS, that would be helpful to include.
edit
It seems that the JS Array is like an object literal with special properties. However, I'm interested in a lower level of detail--how browsers implement this in their respective JS engines.
There cannot be any single correct answer to this qurstion. An array's mechanism for expanding is an internal implementation detail and can vary from one JS implementation to another. In fact, the Tamarin engine has two different implementations used internally for arrays depending on if it determines if the array is going to be sequential or sparse.
This answer is wrong. Please see #Samuel Neff's answer and the following resources:
http://news.qooxdoo.org/javascript-array-performance-oddities-characteristics
http://jsperf.com/array-popuplation-direction
Arrays in JavaScript don't have a capacity since they aren't real arrays. They're actually just object hashes with a length property and properties of "0", "1", "2", etc. When you do .push() on an array, it effectively does:
ary[ ary.length++ ] = the_new_element; // set via hash
Javascript does include a mechanism to declare the length of your array like:
var foo = new Array(3);
alert(foo.length); // alerts 3
But since arrays are dynamic in javascript there is no reason to do this, you don't have to manually allocate your arrays. The above example does not create a fixed length array, just initializes it with 3 undefined elements.
// Edit: I either misread your question or you changed it, sorry I don't think this is what you were asking.