Faking a VbScript Array with JavaScript - javascript

I'm using and testing a VbScript API using JavaScript. One part of the VbScript API has a construct, that I must assume is an array, that you can read and write from. I do not have the source code for the VbScript API, nor do I even have access to the system in which it runs for the time being. In my JavaScript test code, which mocks myObj and myFunc, assignments throw an error, not surprisingly, since I'm mocking it as a function.
myObj.myFunc("xyz") = 1
Mocking as an array would not work, since JavaScript uses [] as the accessor.
One solution would be to wrap calls to myFunc with JavaScript, but I was wondering if there might be a more ingenious solution, JavaScript being the pliable language that it is.
I think I've answered my own question here... I only need to set and read one value, which is why it was not already wrapped and mocked as an array. The answer is to go ahead and wrap it.
Thanks,
Mike

How about this?
myObj.setValue("xyz", 1);
Really it makes no sense trying to simulate the syntax of another language.

I don't exactly understand the question, but if you're trying to create a JS construct that can set an array element using that format, that's pretty easy
Array.prototype.setValue = function(key,value) {
this[key]=value;
};
http://jsfiddle.net/gcVSq/

Related

How do I know JavaScript return types automatically for non-primitives/user-defined types and promises?

I'm working with an SDK and I want to go through all the namespaces shown in its API documentation and verify that all the functions return the correct type of object or if the function returns a promise. However, there are way too many functions to try this manually.
I came across ES6 Iterate over class methods and that might work for functions that don't require input variables but many of the functions in the API I want to try out require inputs as well. It seemed like maybe passing in the .js file process it externally using something like Python might be a good idea but I haven't been able to identify a solution yet.
Overall, I would like to be able to compare all the expected return types from the API documentation vs actual return types for the respective functions and put up the differences on an excel sheet for later use.
The first approach you should try is to see if there is a documentation for the SDK/API where you can read and see what the expected return values are. Due to the fact that it is a JavaSvript api, you kind of need that, or need to read through the code yourself, to know what ALL possible return values are.
If the code itself is documented with JSDocs tags, you could check what they are defined to return, something that most IDE's have support to show you during your coding.
JavaScript is a dynamically typed language, I.E., a function could basically return anything. So the best way to know what you should expect is to check for documentation!

Leaking arguments when using Function.apply

I was reading on GitHub in petkaantonov/bluebird on Optimization killers. And when reaching chapter 3.3 what-is-safe-arguments-usage specifically the part What is safe arguments usage? I realized that I might be going wrong using bind and apply in my project.
The post states:
Be aware that adding properties to functions (e.g. fn.$inject =...) and bound functions (i.e. the result of Function#bind) generate hidden classes and, therefore, are not safe when using #apply.
I used this answer on the question Use of .apply() with 'new' operator. Is this possible? to be able to pass an array of arguments to my constructor function like this:
new (Cls.bind.apply(Cls, arguments))();
This looks suspiciously much like what is described as not safe in the post.
Is this true? Am I going wrong here?
I would simply like to understand if the issue in the post applies to this example case, especially because it might be useful to comment on the answer so others don't make the same error (the post is heavily upvoted so it seems people are using this solution a lot).
Note: I recently found out about the spread operator (awesome) which is a nice alternative, to my previous solution:
new Cls(...arguments);

localStorage - use getItem/setItem functions or access object directly?

Are there some benefits of using the methods defined on the localStorage object versus accessing the object properties directly? For example, instead of:
var x = localStorage.getItem(key);
localStorage.setItem(key, data);
I have been doing this:
var x = localStorage[key];
localStorage[key] = data;
Is there anything wrong with this?
Not really, they are, basically, exactly the same. One uses encapsulation (getter/setter) to better protect the data and for simple usage. You're supposed to use this style (for security).
The other allows for better usage when names(keys) are unknown and for arrays and loops. Use .key() and .length to iterate through your storage items without knowing their actual key names.
I found this to be a great resource : http://diveintohtml5.info/storage.html
This question might provide more insight as well to some: HTML5 localStorage key order
Addendum:
Clearly there has been some confusion about encapsulation. Check out this quick Wikipedia. But seriously, I would hope users of this site know how to google.
Moving on, encapsulation is the idea that you are making little in and out portals for communication with another system. Say you are making an API package for others to use. Say you have an array of information in that API system that gets updated by user input. You could make users of your API directly put that information in the array... using the array[key] method. OR you could use encapsulation. Take the code that adds it to the array and wrap it in a function (say, a setArray() or setWhateverMakesSense() function) that the user of your API calls to add this type of information. Then, in this set function you can check the data for issues, you can add it to the array in the correct way, in case you need it pushed or shifted onto the array in a certain way...etc. you control how the input from the user gets into the actual program. So, by itself it does not add security, but allows for security to be written by you, the author of the API. This also allows for better versioning/updating as users of your API will not have to rewrite code if you decide to make internal changes. But this is inherent to good OOP anyhow. Basically, in Javascript, any function you write is a part of your API. People are often the author of an API and it's sole user. In this case, the question of whether or not to use the encapsulation functions is moot. Just do what you like best. Because only you will be using it.
(Therefore, in response to Natix's comment below...)
In the case here of JavaScript and the localStorage object, they have already written this API, they are the author, and we are its users. If the JavaScript authors decide to change how localStorage works, then it will be much less likely for you to have to rewrite your code if you used the encapsulation methods. But we all know its highly unlikely that this level of change will ever happen, at least not any time soon. And since the authors didn't have any inherent different safety checks to make here, then, currently, both these ways of using localStorage are essentially the same. Except when you try to get data that doesn't exist. The encapsulated getItem function will return null (instead of undefined). That is one reason that encapsulation is suggested to be used; for more predictable/uniform/safer/easier code. And using null also matches other languages. They don't like us using undefined, in general. Not that it actually matters anyhow, assuming your code is good it's all essentially the same. People tend to ignore many of the "suggestions" in JavaScript, lol! Anyhow, encapsulation (in JavaScript) is basically just a shim. However, if we want to do our own custom security/safety checks then we can easily either: write a second encapsulation around the localStorage encapsulate, or just overwrite/replace the existing encapsulation (shim) itself around localStorage. Because JavaScript is just that awesome.
PT
I think they are exactly the same, the only thing the documenation states is:
Note: Although the values can be set and read using the standard
JavaScript property access method, using the getItem and setItem
methods is recommended.
If using the full shim, however, it states that:
The use of methods localStorage.yourKey = yourValue; and delete
localStorage.yourKey; to set or delete a key is not a secure way with
this code.
and the limited shim:
The use of method localStorage.yourKey in order to get, set or delete
a key is not permitted with this code.
One of the biggest benefits I see is that I don't have to check if a value is undefined or not before I JSON.parse() it, since getItem() returns NULL as opposed to undefined.
As long as you don't use the "dot notation" like window.localStorage.key you are probably OK, as it is not available in Windows Phone 7. I haven't tested with brackets (your second example). Personally I always use the set and get functions (your first example).
Well, there is actually a difference, when there is no local storage available for an item:
localStorage.item returns undefined
localStorage.getItem('item') returns null
One popular use case may be when using JSON.parse() of the return value: the parsing fails for undefined, while it works for null

What's a clean way to handle ajax success callbacks through a chain of object methods?

So, I'm trying to improve my javascript skills and get into using objects more (and correctly), so please bear with me, here.
So, take this example: http://jsfiddle.net/rootyb/mhYbw/
Here, I have a separate method for each of the following:
Loading the ajax data
Using the loaded ajax data
Obviously, I have to wait until the load is completed before I use the data, so I'm accessing it as a callback.
As I have it now, it works. I don't like adding the initData callback directly into the loadData method, though. What if I want to load data and do something to it before I use it? What if I have more methods to run when processing the data? Chaining this way would get unreadable pretty quickly, IMO.
What's a better, more modular way of doing this?
I'd prefer something that doesn't rely on jQuery (if there even is a magical jQuery way), for the sake of learning.
(Also, I'm sure I'm doing some other things horribly in this example. Please feel free to point out other mistakes I'm making, too. I'm going through Douglas Crockford's Javascript - The Good Parts, and even for a rank amateur, it's made a lot of sense, but I still haven't wrapped my head around it all)
Thanks!
I don't see a lot that should be different. I made an updated version of the fiddle here.
A few points I have changed though:
Use the var keyword for local variables e.g., self.
Don't add a temporary state as an object's state e.g., ajaxData, since you are likely to use it only once.
Encapsulate as much as possible: Instead of calling loadData with the object ajaxURL, let the object decide from which URL it should load its data.
One last remark: Don't try to meet requirements you don't have yet, even if they might come up in the future (I'm referring to your "What if...?" questions). If you try, you will most likely find out that you either don't need that functionality, or the requirements are slightly different from what you expected them to be in the past. If you have a new requirement, you can always refactor your model to meet them. So, design for change, but not for potential change.

javascript profile in Firefox

(I know some people already asked questions about js profile, but that's not what I need if I understand them correctly.)
I'd like to trace the execution of javascript to collect the information of 1) which function is invoked, 2) the time when the function is invoked, and 3) the execution time of the function.
I want to collect the information online (on deployed code) but not in-house. So, the trade-off has to be light. Also, I don't want to manually add a line before and after where a function is invoked. However, it would be great if there's a way that can dynamically instrument the code.
Thanks in advance!
I don't think that there is any system whereby JavaScript will automatically track the time a function starts and the time a function stops. That is likely something you will have to add yourself. If this is what you need, you may want to consider using PHP to serve up your JavaScript and use a regular expression to find the beginnings and ends of each function with a regex or something like that.
Your RegExp might look like this (completely untested, so you'll have to experiment):
/function [A-Za-z_$][A-Za-z0-9_$]*{(.*?)}/i
Once you have access to the inside of the function, you could replace that value with the function to track its beginning and end wrapped around the original function definition.
This has the benefit of doing exactly what you want, without worrying about modifying how your js code functions. It is then something the server will handle entirely.
Either that or, instead of calling the function directly, use a wrapper function:
function wrapFunction( func, context, argList )
{
// Replace with however you are storing this.
console.log( new Date().getTime() );
func.apply( context, argList );
console.log( new Date().getTime() );
}
This has the benefit of being a lot cleaner than having the server update your JS for you. Unfortunately, it also means having to re-write the JS manually.
My recommendation would be to simply adapt a logging syntax and use that. Most loggers will output a timestamp, a context, a level, and a specific message. If you simply call the logger at the beginning and end of the function, it will do exactly what you're looking for. Further, since many are configurable, you would be able to have it display to the JS console in Firefox, send information to the server, or completely disabled if you so chose.
There are a list of JS loggers here:
JavaScript loggers
This would unfortunately require you to manually update everything, but it seems like the simplest way to get 90% of what you're looking for out of the box.
Perhaps the profiler in FireBug can help you track down slow functions.
Here's a video detailing the profiling options. (Index: 3:20).
console.profile([title])
//also see
console.trace()
http://getfirebug.com/wiki/index.php/Console_API

Categories

Resources