I'm using three.js in a js project and I'm trying to calculate if a vector is still in an area like this
var THRESHOLD = 10;
if(!is_in_rect(camera.position - forward * THRESHOLD)))
// do something
where camera.position and foward are THREE.Vector3 objects.
The problem with the approach above, although very readable, is that it's not working since js doesn't support operator overloading. I have to write something like
if(!in_rect(camera.position.clone().add(forward.clone().multiplyScalar(THRESHOLD)))
which looks kinda ugly to me.
Is there any other idiomatic way of doing this in js that I'm missing?
From the page you linked to:
.addScaledVector ( v, s )
Adds the multiple of v and s to this vector
so a bit better is:
camera.position.clone().addScaledVector(forward,THRESHOLD)
Also, there's no real reason to clone forward, as that won't be changed.
If I'm following what #T.J. is saying, and you want something more general, than my answer would be no, if idomatic means using + and -, if we're strictly sticking to JS. You could build your own framework to make things idomatic, such as a general addition operator:
var add = function(x,y):
try {
var sum = x + y;
if ( s != undefined ) { return sum; }
#otherwise
sum = x.clone().add(y);
} catch {
#Otherwise threw something
sum = x.add(y) #maybe another exception? nest try/catch.
}
}
But this is a lot of work, as you would have to type check a lot since JS can add up stuff with impunity. Just trying to return x+y will often be undefined. In my example perhaps testing for add functions before simple additions may be better.
This way you can create the idiom you like, if you think it's worth it, and use your add for everything (instead of + in my example). Probably grow it as you code.
Is there any other idiomatic way of doing this in js that I'm missing?
Not really, no; you'd basically have to write yourself an expression parser, or use one that's already been written.
A couple of notes on that:
Doing that might be a bit easier with ES2015+'s template literals and tagged template functions, since it would do some of the parsing for you. For instance, you might be able to give yourself tag function that would let you write:
if(!is_in_rect(threval`${camera.position} - ${forward} * ${THRESHOLD}`)))
threval would receive an array of the raw strings in that template, followed by the values of camera.position, forward, and THRESHOLD. So you could use that information to build up the sequence. But it would be non-trivial.
You could write yourself a Babel plugin to make your expressions first-class productions, and transpile. The advantage to that is that Babel provides a robust parsing infrastructure and tooling support.
Related
So to clarify the question, I understand what an IIFE and object literal is. However, I am unsure what the difference(s) is/are between these two examples (aside from the fact that one is a function and the other is an object literal):
Example 1:
(function(){
var myStuff = {
arbitraryValue: 42
}
return myStuff.arbitraryValue;
})();
Example 2:
(function(){
var myStuff = function() {
return {
arbitraryValue: 42
};
}
return myStuff().arbitraryValue;
})();
Both examples return the same results, and are called (almost) the same way. But:
1) What are the fundamental differences between them?
2) Is there a benefit to using one over the other?
3) I've seen code where (in the 2nd example) return myStuff.arbitraryValue works just the same as return myStuff().arbitraryValue. How is that possible?
4) Is this overkill if I'm just trying to avoid global conflicts and write clean code?
5) Are either of these examples considered "best practice," or is there another option?
Many thanks in advance!
1) What are the fundamental differences between them?
The first (probably) uses less CPU cycles because it has one less function call and is less to write. It's also easier to understand so is likely easier to maintain.
2) Is there a benefit to using one over the other?
The first uses less code and is likely easier to understand and maintain.
3) I've seen code where (in the 2nd example) return myStuff.arbitraryValue works just the same as return myStuff().arbitraryValue. How is that possible?
Perhaps using get, a feature of JavaScriptâ„¢ but not ECMAScript.
4) Is this overkill if I'm just trying to avoid global conflicts and write clean code?
Yes, though you haven't shown what is done with the returned value. In the example it disappears into the ether.
5) Are either of these examples considered "best practice," or is there another option?
"Best" infers a complarison with other things that are less preferred based on objective criteria. Without those criteria (which might be some of: speed, robustness, maintainability, support or other features, desirable or not) it can't be determined.
If you propose a circumstance where you'd like to use one or the other, advice can be given on whether there are better ways or not based on the criteria suggested (or others you may have) and in comparison to alternatives.
I come from a C# background. I've been working a lot with JavaScript lately. On a new app, I have a mysql/php back end. I'm going to be passing a lot of "types" back and forth.
So in my data base, I have several tables like
table1
id, fieldx,fieldy,fieldz
table2
id, fielda,fieldb,fielc
In c# I would definitely write classes for all those in the code. Which led me to implement things like so (in my JavaScript app):
function table1(id, x,y,z){
this.id=id;
this.x=x;
this.y=y;
this.z=z;
}
After about 6 tables worth of that, it suddenly occurred to me that maybe there was no point at all in making these classes.
So my question is, in a JavaScript app, do I use "classes" for data types? or should I just "document" which fields/types are expected and so in the code instead of
a.push(new table1(5,1,2,3));
I would just have
a.push({id:5,x:1,y:2,z:3});
This may seem like a preferences question but it's a fundamental language question that I have as I try to understand how to model my app's data in JavaScript. Is there any advantage of the classes (with only data fields) or is it just a mistake. Thanks.
It depends,
Note: Most of the programmers coming from a strong OO language will have trouble like you in regard to JavaScript's functional behavior (you are not alone).
If you want to create something closer to C# I would do the following:
function Table1(id, x, y, z) {
this.id=id;
this.x=x;
this.y=y;
this.z=z;
}
Table1.prototype.mySpecialTable1Method= function()
{
console.log(this.id);
};
Implementation:
var t = new Table1(1, 2, 3, 4);
t.mySpecialTable1Method();// outputs: 1
If you need to have methods that interact with the (soon to be) objects then I would definitely go with the code above. In addition it will make it clear when working with the objects that are related to a specific 'type' (naming the data).
But if your objects do not require any special "treatment" then I don't see any problem to use normal js object literals and pass them along (probably good for small projects).
Something along the lines:
var table1 = {};
table1.id = 1;
table1.x = 2;
table1.y = 3;
table1.z = 4;
console.log(table1.id); //outputs: 1
Extra reference:
http://www.youtube.com/watch?v=PMfcsYzj-9M
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Update:
For the sake of readability and scalability and the point that you are coming from C# you may want to stick to the "class" implementation just because it will define the correlation between the raw data and the objects you are working with.
There is a good chance that you are going to work with some data that will probably be messy and unorganized.
MVC may be the solution for you. It tries to bring some order to the chaos that you are expecting. I recommend to check out some of them like: AngularJS or Ember.
Another solution may be reactive js - but mostly if you are going to interact with the DOM according to your data (ReactJS, and Facebook's React as some good ones).
As a note for security, I would like to add that mapping the data closely to the db isn't a best practice but its your call.
Javascript is a funny language, and there are plenty of ways to do things. An Object is an Object in Javascript with or without a name. {} is just a short-hand way to create one.
If you are going for readability, then your initial example would be the way to go.
If you just want to get the block of data into an array, then your second example is appropriate. Personally, I would use your later example if it is just data.
If you are using functions and what not as well as data storage, and plan on reusing it several times in your code, then yes, define your object and call it appropriately.
JavaScript has no classes, it is a functional language and a function is a first class citizen in js meaning that a function is an object.
From your example I can see that your intention for classes is simply to pass data and using json is perfect for this.
This question already has answers here:
What are the Alternatives to eval in JavaScript?
(11 answers)
Closed 7 years ago.
I work mainly with javascript, Jquery, knockout, etc
The thing that attracted eval() to me is
var a = 5;
var b = 10;
eval("a+b");
//Gives me output 15
Note: I work in cases where the value of a and b changes dynamically
In my work I'm dealing with a lot of dynamic objects from json, knockout, etc. So eval solves most of my problems.
But as I read I found there are so many issues with eval() like slowing down etc.
I searched a lot and haven't found any substitute for eval() when i have to evaluate equation obtaining as string into equation as object.
Can anyone suggest a plugin or function alternative to eval() keeping in mind the example i have given above
Problem:
I'm creating a Table from Json data using knockout mapping. So that what ever the format of json is the table is generated. I also calculate some field using knockout computed.
Right now I use hard-coded
self.Salary = ko.computed(function(){ return self.salaryEqn() && eval(self.salaryEqn()).toFixed(2); })
self.salaryEqn(salEqnTxt);
I want to execute these equations dynamic. I can create it dynamicaly as string but to eval them is the issue I'm facing.
I want solution for
Is there a way to calculate a formula stored in a string in JavaScript without using eval?
Like a formula
"self.Salary = ko.computed(function(){ return self.salaryEqn() && eval(self.salaryEqn()).toFixed(2); })"
Javascript is a very flexible language in this regard. There are very very few cases where eval() is the right answer to any given question, and it certainly isn't necessary here.
If your a and b variables are part of an object, you can access them with string subscripts:
ie myobj.a could also be referenced as myobj['a'].
From that, you can use a variable for the subscript, and thus you can reference any element in myobj dynamically -- ie:
var myobj = {a : 5, b : 10};
var dynamicProperty1 = 'a';
var dynamicProperty2 = 'b';
//gives 15.
alert( myobj[dynamicProperty1] + myobj[dynamicProperty2] );
No eval() required. You can build the dynamicProperty strings however you wish, so there's virtually infinite flexibility.
If your a and b variables are globals, JS globals in the browser are actually children of the window object, so you can still use this technique even with globals.
ie your global variable a could also be accessed via window.a or window['a'], with the latter option allowing you to do the same dynamicProperty trick described above.
Hope that helps.
do you mean that you want to calculate an equation that you can't know until you've received it?
if so see Calculate string value in javascript, not using eval .
in short:
eval CAN be used sometimes, but only if the equation string comes from a trusted source, and there you need something like evaluating dynamic equations.
maybe using window['var' + num] might be more useful for you. i don't quite understand your question sorry.
If you can collect them under an object like root = {a: 1, b: 2}, then
Object.observe(root, function(newValues) {
res = newValues.object.a + newValues.object.b;
});
can keep your res variable up to date whenever the a or b changes
It looks like you are trying to do dynamic equations created by a user.
For example it could be 'a+b+c' or 'dog+cat', and you don't know.
The best way to handle user-input equations like that is to parse the text into tokens and then translate the tokens into values/operands.
That's a lot of work, but there are pre-rolled solutions. For example, math.js
Check more alternatives to eval in this question and another one here which both might be considered a duplicate...
I understand this is a link only answer, but it will for sure be helpful to others searching for alteratives to eval.
I've been working with node.js for a while on a chat app (I know, very original, but I figured it'd be a good learning project). Underscore.js provides a lot of functional programming concepts which look interesting, so I'd like to understand how a functional program in JavaScript would be setup.
From my understanding of functional programming (which may be wrong), the whole idea is to avoid side effects, which are basically having a function which updates another variable outside of the function so something like
var external;
function foo() {
external = 'bar';
}
foo();
would be creating a side effect, correct? So as a general rule, you want to avoid disturbing variables in the global scope.
Ok, so how does that work when you're dealing with objects and what not? For example, a lot of times, I'll have a constructor and an init method that initializes the object, like so:
var Foo = function(initVars) {
this.init(initVars);
}
Foo.prototype.init = function(initVars) {
this.bar1 = initVars['bar1'];
this.bar2 = initVars['bar2'];
//....
}
var myFoo = new Foo({'bar1': '1', 'bar2': '2'});
So my init method is intentionally causing side effects, but what would be a functional way to handle the same sort of situation?
Also, if anyone could point me to either a Python or JavaScript source code of a program that tries to be as functional as possible, that would also be much appreciated. I feel like I'm close to "getting it", but I'm just not quite there. Mainly I'm interested in how functional programming works with traditional OOP classes concept (or does away with it for something different if that's the case).
You should read this question:
Javascript as a functional language
There are lots of useful links, including:
Use functional programming techniques to write elegant JavaScript
The Little JavaScripter
Higher-Order JavaScript
Eloquent JavaScript, Chapter 6: Functional Programming
Now, for my opinion. A lot of people misunderstand JavaScript, possibly because its syntax looks like most other programming languages (where Lisp/Haskell/OCaml look completely different). JavaScript is not object-oriented, it is actually a prototype-based language. It doesn't have classes or classical inheritance so shouldn't really be compared to Java or C++.
JavaScript can be better compared to a Lisp; it has closures and first-class functions. Using them you can create other functional programming techniques, such as partial application (currying).
Let's take an example (using sys.puts from node.js):
var external;
function foo() {
external = Math.random() * 1000;
}
foo();
sys.puts(external);
To get rid of global side effects, we can wrap it in a closure:
(function() {
var external;
function foo() {
external = Math.random() * 1000;
}
foo();
sys.puts(external);
})();
Notice that we can't actually do anything with external or foo outside of the scope. They're completely wrapped up in their own closure, untouchable.
Now, to get rid of the external side-effect:
(function() {
function foo() {
return Math.random() * 1000;
}
sys.puts(foo());
})();
In the end, the example is not purely-functional because it can't be. Using a random number reads from the global state (to get a seed) and printing to the console is a side-effect.
I also want to point out that mixing functional programming with objects is perfectly fine. Take this for example:
var Square = function(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
};
function getArea(square) {
return square.w * square.h;
}
function sum(values) {
var total = 0;
values.forEach(function(value) {
total += value;
});
return total;
}
sys.puts(sum([new Square(0, 0, 10, 10), new Square(5, 2, 30, 50), new Square(100, 40, 20, 19)].map(function(square) {
return getArea(square);
})));
As you can see, using objects in a functional language can be just fine. Some Lisps even have things called property lists which can be thought of as objects.
The real trick to using objects in a functional style is to make sure that you don't rely on their side effects but instead treat them as immutable. An easy way is whenever you want to change a property, just create a new object with the new details and pass that one along, instead (this is the approach often used in Clojure and Haskell).
I strongly believe that functional aspects can be very useful in JavaScript but ultimately, you should use whatever makes the code more readable and what works for you.
You have to understand that functional programming and object oriented programming are somewhat antithetical to each other. It's not possible to both be purely functional and purely object oriented.
Functional programming is all about stateless computations. Object oriented programming is all about state transitions. (Paraphasing this. Hopefully not too badly)
JavaScript is more object oriented than it is functional. Which means that if you want to program in a purely functional style, you have to forego large parts of the language. Specifically all the object orient parts.
If you are willing to be more pragmatic about it, there are some inspirations from the purely functional world that you could use.
I try to adhere to the following rules:
Functions that perform computations should not alter state. And functions that alter state should not perform computations. Also, functions that alter state should alter as little state as possible. The goal is to have lots of little functions that only do one thing. Then, if you need to do anything big, you compose a bunch of little functions to do what you need.
There are a number of benefits to be gained from following these rules:
Ease of reuse. The longer and more complex a function is, the more specialized it also is, and therefore the less likely it is that it can be reused. The reverse implication is that shorter functions tend to more generic and therefore easier to reuse.
Reliability of code. It is easier to reason about correctness of the code if it is less complex.
It is easier to test functions when they do only one thing. That way there are fewer special cases to test.
Update:
Incorporated suggestion from comment.
Update 2:
Added some useful links.
I think, http://documentcloud.github.com/underscore/ should be nice fit for what you need - it provides the most important higher-order functions for functional programming and does not has client-side functions for DOM manipulation which you don't need for server side. Though I don't have experience with it.
As a side note: IMHO primary feature of functional programming is Referential transparency of a function - function result depends only on its parameters - function does not depend on changes on other objects and does not introduce any change except its result value. It makes it easy to reason about program's correctness and very valuable for implementing of predictable multi-threading (if relevant). Though JavaScript is not the bet language for FP - I expect immutable data structures to be very expensive performance-wise to use.
So 2 things to point out ,
In your first example your variable would not be leaking into the global area and is the way it should be done , try to never use variables without declaring them i.e. test = 'data' would cause data to leak into the global area.
Your second example is correct as well , bar1 and bar2 would only be declared on the Foo object.
Things to keep in mind try not to overuse prototyping since it applies to every object that you create , this could be extremely memory intensive depending on how complex your objects are.
If you are looking for a app development framework , have a look at ExtJs. Personally I think it would fit perfectly into the model you are trying to develop against. Just keep in mind how their licensing model works before getting heavily invested in it.
I've always wondered why Javascript has the global Math object instead of giving numbers their own methods. Is there a good reason for it?
Also are there any drawbacks (other than efficiency) to doing something like this?:
Number.prototype.round = function(){
return Math.round(this);
};
Just to make clear, I understand that constants like π need somewhere and functions that are applied on more than one number like min/max. The question was mainly concerning methods which only effect a single number such as round, abs, sin, pow, etc.
The reason for the Math object is simple: "because Java does it". Not the best of reasons, but here we are. I guess things made more sense back then, before Douglas Crockford started his campaign to suppress half the language*. Originally you were "allowed", or meant, to do things like this:
with (Math) {
var n = min( round(a) * round(b), sqrt(c) );
var result = exp( n + d );
}
The drawback to extending Number.prototype is that someone else might do the same thing. Or worse, for example, define Number.prototype.round as a symmetrical rounding function.
If you are looking for ways to make your life easier, why stop there? Why not simply include Math functions as global functions?
var m = 'abs acos asin atan atan2 ceil cos exp floor log max min ' +
'pow random round sin sqrt tan PI').split(' ');
for (var i=0,l=m.length; i<l; i++) {
window[ m[i] ] = Math[ m[i] ];
}
This will drop all the math functions into the global scope, effectively allowing you to stop typing "Math." Ask yourself: Is there any real difference between extending Number and extending window with these functions?
* Before you flame me: The Crockford comment is not meant to be taken too seriously. I do agree with him that with is very dangerous in an implicit global environment.
There is no drawback in extending Number.prototype other than confusing other people. What's the point? What is better in using value.round() instead of Math.round(value)?
There are several good reasons for the Math object:
It works for non-numbers, too: Math.round("5") works whereas value.round() won't work when value is a string (for example, the value of a textbox)
Some members of the Math object don't belong to a "primary" number value, like Math.min() or Math.max(). Or do you want to use it like a.max(b)?
Other members are global and do not belong to a specialized number. Examples are constants like Math.PI or the function Math.random().
Try doing 123.round();
Your javascript console will throw a few hundred of errors to your eyes :P, nah ...
You can do:
Number.prototype.x then: (123).x(); but never 123.x();
I think Math is more than set of Number methods. It's usage wider. Say, using NumberVariable.PI can be confusing. Same with random numbers generation.
Also I think extending number is OK, because it's the part of JS nature. Maybe someone will correct me if I am wrong here.
I believe calling it this way works as well, since Number's prototype functions work just like every other Object's prototype functions do:
5.5["round"]();
//should return 6
So, the conversation on whether its a good idea or not aside, you can do this fine.
You can do 123.x() but the interpreter for js is broken (as it doesn't interpret the dot as a message dispatch)
Weirdly, you can use 123 .x() (with a space between the number and the dot) instead, and it'll work.
123..also works but that's because you've effectively made a decimal and then dispatching to it
(typeof 123.) === 'number') // true
Try:
Number.prototype.times = function(other) { return this * other }; 3 .times(5);
in the console.
My view on this is that if you do the proper checks as to not overwrite native functionality, name with understanding of native naming standards and it makes your code more readable and manageable, then make your code comfortable and convenient.
if (Number.prototype.round == null)
Number.prototype.round = function() { return Math.round(this); }
AS for using this, because of the nature of javascript, I believe the best way to do this is by:
Wrapping the number in a variable instead of a simple static value (Most often the case)
nNum.round();
Wrapping the simple static value in parentheses :
(123).round();
Calling using square bracket notation
123["round"].call();
You can do this
Number.prototype.round = function() {
return Math.round(this.valueOf());
};
https://www.w3schools.com/jsref/jsref_prototype_num.asp