Call JS Math functions without writing Math.__ every time? - javascript

I have some code that uses JavaScript’s Math functions quite a lot, to the point that I’d much rather be writing things like exp(cos(PI/2)) instead of Math.exp(Math.cos(Math.PI/2)), which gets ugly and unreadable fast. Even an alias like m. would be clutter. To that extent, I need a simple bit of header code to enumerate over Math and pull its entries into the current scope.
Good news is, standing on the shoulders of Stack Overflow giants, I’ve built an elegant solution to share with the world!! 🥳 Here it is:
// Import all Math numbers and functions to the current (global) scope.
for (let name of Object.getOwnPropertyNames(Math))
globalThis[name] = Math[name]
console.log( exp(cos(PI/2)) ) // = 1
Codepen
I’m very happy with it, posting it here to give back to the community and to see if anyone has improvements! 💞 It truly just feels so much cleaner now, like how it should’ve always been. Math functions deserve to be global!

Posted above!
// Import all Math numbers and functions to the current (global) scope.
for (let name of Object.getOwnPropertyNames(Math))
globalThis[name] = Math[name]
console.log( exp(cos(PI/2)) ) // = 1
Codepen

Related

Why is there a need for javascript coding conventions?

Suppose I have to write a javascript function:
function(){
var a=1;
var sum=1;
for(var i=0;i<6;i++){
sum=sum+a+1;
}
console.log(sum);
}
Someone recommended me to write this function like this:
function () {
var a = 1;
var sum = 1;
for (var i = 0; i < 6; i++) {
var sum = sum + a +1;
}
console.log(sum);
}
With more blank space, I know this rule, but I don't how it works, or what can I benefit from it?
It is a matter of opinion what good style is, but in a general sense picking some style and consistently following it throughout your code makes it easier to read (both for other people and for you when you come back to it later).
In my experience most people find code easier to read with the extra spaces as shown in your second example.
I don't like putting a space between function and (). Or, where there is a function name I don't put a space between the name and the parentheses: function someName().
Note also that with modern code editors that have syntax highlighting (like Stack Overflow does) it is much easier than it used to be to read code that doesn't have spaces. Compare the following two:
for(var i=0;i<6;i++)
for(var i=0;i<6;i++)
Reading and editing the latter, all in black and white, really annoys me, but I don't mind the coloured version anywhere near as much. I still prefer it with the extra spaces though.
I'd make some other changes in your function:
function() {
var a = 1,
sum = 1,
i;
for(i = 0; i < 6; i++){
sum += a + 1;
}
console.log(sum);
}
The benefit of coding style is enhanced readability. It does not really matter what style you decide to stick to, as long as you DO stick with a uniform style, and can agree with your coworkers on its readability, which is not always easy.
These coding conventions are for humans, they increase readability. Suppose I have written an expression like this:
x=(a*b/2)+m-n+c*(d/e);
It looks clumsy and difficult to read. It would have been easier to understand if we had used spaces around operators like this:
x = (a * b / 2) + m - n + c * (d / e);
Again using blank line increases readability by denoting sections. For example:
function foo() {
var a;
var b;
// a blank line here to specify the end of variable declarations
if (some_cond) {
} else if (another_cond) {
}
// another blank line to specify end of some logic
//more codes here;
}
If you do not follow these guidelines and all team members do not agree in some convention then it will be very difficult to maintain a big project for long time.
Finally note that, the conventions are not for compilers, they are for humans. That's why it is called coding guidelines, not language syntax.
May be you should read more about javascript closure, and you can follow "Google Javascript Style Guide".
Following some uniform style guidelines when coding makes code easier to read and helps you writing beautiful code, and others understanding (and loving!) your code.
For sure there are loads of resources on the net (just by googling for a while you get some javascript guides or guidelines), but this one is quite easy, simple and complete:
http://javascript.crockford.com/code.html
It's not a rule. It's just coding convention style. You don't need to follow if you don't want. But this style can make your code more readable, easier to maintain, and cleaner. To me, I prefer to have space rather than narrow letters. Again, it's not a rule.
Coding style is always very personal; one person likes condensed code so that they can see as much as possible on one screen, another needs the opening and closing braces on a separate line, etc.
When only coding for yourself, you should choose whatever is best for you. But when you start working in teams and others have to maintain your code and visa versa, it becomes important to agree on one coding style ... and this can be hard.
I've sat in coding style discussions and they're very uncomfortable, because you're giving up some of your personal preferences albeit for the greater good. After a brief moment of discomfort you will get used to it ;-)
The second version isn't equivalent to the first, as it declares an inner 'sum' variable, unless Javascript doesn't do what it says on the tin with that.
The extra blank lines don't contribute anything much IMHO, but I probably wouldn't die in a ditch about them. However an equally valid concern is download speed, which is made worse by the suggestion.

What is "excessive trickness"?

After reading Douglas Crockford's "JavaScript: The Good Parts" and Stoyan Stevanov's "JavaScript Patterns," I'm trying to determine exactly what 'excessive trickiness' means. They both say that this occours when using either ++ or -- in your code, but can't find a firm definition for this term, either within SO or via a Google search. Any ideas?
You can hear it from Crockford himself here: http://www.youtube.com/watch?feature=player_detailpage&v=47Ceot8yqeI#t=4140s
The simple answer is that ++ and -- act on a variable, and usually do it at the same time as you're doing something else to that variable. For example, can you quickly decide what this does?
y += x++ + ++y; // what is y now?
More StackOverflow discussion: Why avoid increment ("++") and decrement ("--") operators in JavaScript?
It's about the little tricks that are built-in. For example, avar++ is an alias for avar = avar + 1.
JavaScript is filled with operators and other things that make programming easier, but they are just tricks. That's probably what he means.
Also, as Jonathan pointed out: Why avoid increment ("++") and decrement ("--") operators in JavaScript?
Excessive trickiness is subjective. Because of that, there's no firm definition for it.
Some would say the C famous string copy code (while (*p++ = *q++);) is excessively tricky, some would say it's not.
Here is a fairly lengthy discussion with links:
Why avoid increment ("++") and decrement ("--") operators in JavaScript?
I think part of the idea is that when using those operators anywhere but with a single variable on a single line, they become confusing to anyone not in the developer's head.

Performance & "Better Practice": with statement vs. function with a bunch of parameters

I've been doing a lot of templating in JS lately, so I've invariably run across the "evil" with statement.
It makes templates much easier to work with as you don't have to preface your variables with an object.
Hearing that with statements are bad and also that they may cause poor performance, I set out for another solution:
My Solution: Function with a bunch of parameters
Here's my code:
var locals = {
name : "Matt",
email : "wahoo#wahoo.com",
phone : "(555) 555-5555"
};
var keys = [];
var values = [];
for (key in locals) {
local = locals[key];
keys.push(key)
values.push(local);
}
keys = keys.join(',');
var fn = new Function(keys, "**TEMPLATE STUFF**"); // function(name, email, phone) {...}
fn.apply(this, values); // fn("Matt","wahoo#wahoo.com","(555) 555-5555")
Note: these accomplish the exact same thing. Both are abstracted away from anyone so an obnoxiously long parameter list is no biggie.
I'm wondering which one is better: using a with statement or a function with the potential for a crazy number of parameters.
Unless someone has a better solution...?
Thanks!
Matt Mueller
I find your solution very bloated. It is totally non-trivial, while with is so simple (one line of code which in and of itself has very little cost vs. your object traversal and array instantiations).
Moreover, your solution requires a template object ready when making the templating function (to define its parameters), which may prove down the road less flexible in my opinion.
Check out MDC. A well designed template would presumably have little logic and heavy variable references (and if it isn't that way, then it should be!), which makes with the perfect candidate in such a situation, because there should be very few other lookups in the scope of the with.
Any extra performance that may be gained seems like it would be micro-optimisation, although rather than theorise, just perform some benchmarks. http://jsperf.com/with-vs-fn does all the setup code before the benchmark for your version, but performs the with stuff during the function execution, so it's not really fair, although even on the slowest iterations you get an idea of how fast it is; >400,000 ops/sec is the slowest. I doub't you need to render more than 400,000 templates a second...
Have you tried a JS templating engine? They are usually very fast, and save you some rendering code.
I'm the author of pure.js which is a bit original, but there are plenty of others available and for any taste.
The problems with with are not performance, they are ambiguity and unpredictable behaviour.
See, for example, Hidden Features of JavaScript?

Current project tells me I need to look at Javascript OOP, should I? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm working on (and have actually finished) a project that fetches price quotes based on user-entered data. I've written the code already and it works fine. It's written in javascript/jQuery using events and functions, more like this (example I just wrote for this question, not actual code):
// event - when the quantity field changes
$('input[name=quantity]').change(function(){
// get the product
var product = $('input[name=product]').val();
// run function to set the base price
setBasePrice(this.value,product);
});
// function - set the base price
function setBasePrice(quantity,product){
var basePrice = quantity * getTierPrice(quantity,product);
// show the base price to user
$('.basePrice').empty().val(basePrice);
};
// function - set price based on quantity and product
function getTierPrice(quantity,product){
// switches through 6 tiers (based on quantity)
// e.g. - If product is x and quantity is y, price = z
// returns a value
};
There are many more working parts but I wrote that to illustrate how it's put together. It just seems really verbose and a lot of moving parts. When it comes time to update it, it's a pain.
But I'm wondering if I should be using OOP for something like this? I really just want to get to the root of javascript best practice and find out how something like this should really be put together. I feel like a lot of the code I write, although works, isn't always the best way, maybe it's because I am self taught and haven't really dug in deep enough.
I broke the functionality into pieces if it helps to understand what is going on. It's not crucial for you to understand how every bit works:
Things I'm expecting
= zip code (number)
= product (string)
= quantity (number)
- Need to verify number is between x and y (e.g. - 100 to 10000)
= artwork colors (number)
- Need to verify number is between x and y (e.g. - 0 to 6)
Things I'm calculating
= base price (number)
- Depends on the product selected
- Depends on the quantity entered (6 tiers of pricing based on quantity)
e.g. - "Product 1" quantity of 101 to 200 = $9, quantity of 201 to 300 = $7, etc
= screen charge (number)
- Depends on the number of artwork colors entered
- Depends on the quantity entered (uses same tier as when calculating base price)
e.g. - "Product 1" quantity of 101 to 200 add 1.00 per artwork color
- Gets rolled into the base price
e.g. - base price = base price + (artwork colors*quantity);
= shipping cost (hits url via ajax to fetch rate, returns number)
- Depends on zip code entered
- Depends on product selected (each product has different weight)
Things I need to output
= final price
= shipping cost
= base price
So should I be using OOP, should I look at the YUI Module Pattern? If so, at a high level, how would I start? I don't need a full code sample, just an idea of where to begin. I really want my code to look good and be structured properly. Any advice, resource links, etc is greatly appreciated.
My general test for "should I make this chunk of free floating functions in to a set of methods on a class" (which applies to any language, not just JS), is simple: am I passing the same variables around all over the place?
If so, I think it helps matters to make those variables in to fields of a class, and then make those functions in to methods, because then all of those methods can reference all of those variables, without you having to pass everything around "by hand". Furthermore, you can control things much better this way.
For instance, let's say you have several functions that takes a "foo" argument and call "setBar" on it, then set a "dirty" flag on it. With that setup, it's easy to accidentally forget to set the "dirty" flag. However, by making foo a field, and creating a setFooBar method (which calls "setBar" and sets the "dirty" flag), you can ensure that the "dirty" flag always gets set.
Anyhow, I can't tell from the limited code examples you've provided whether your code passes the test, but hopefully this gives you some food for thought.
What you could do, is look into the MVC-paradigm - an architectural separation of logic that aims to abstract your code's components into Models, Views and Controllers. It's mostly known in frameworks for backend-languages (CakePHP for PHP, Rails for Ruby, Django for Python etc.), but is absolutely also applicable to JS.
See this post for some handy references. Personally, Backbone seems like an easy light-weight place to start off (and it supports jQuery (as I saw you referred too)).
All the javascript work you can do only by functional scripting can be done by oop scripting and vice versa.
In most cases, using javascript as an OOP language is more elegant and powerfull, but not necessarily more efficient.
When I started to put toghether the javascript OOP basics , I was so fascinated by the prototipical inheritance , that i used objects everywere... until I realized that I was complicating everything (ex: instead of a normal 2-line image preloader script, I started coding ImgObjects that were much more complex than my original task required).
From the little code you provided, I can't really tell if OOP would bring major improvements on your project, but i suggest you take a peak at prototipal inheritance and maby some design patterns (this book is amazing), but don't forget that javascript is a fully functional language!
i always promote oop! i think javascript works quite ok as oop language. there's a book called "javascript patterns" from o'reilly. it's written by some yahoo guru named stoyan stefanov, and it's very good at explaining when to use oop in js, and how to do it in a good way.
according to this book, i think that you would make an object that has a constructor taking your input data, validating it, and then saving to members. then it would have some methods for performing the calculations you write about. and those calculations would be made with the help of the members stored during object creation.
here's an example class:
//class named SomeClass
//constructor taking two arguments named init1 and init2
function SomeClass(init1, init2) {
//members, use of keyword "var" makes them private
//logic makes the members have validated values, if input is not satisfying
var m_init1 = init1 > 5 ? init1 : 5;
var m_init2 = init2;
//so that was the constructor
//well, this is still the constructor, but
//conceptually, it's not anymore.
//here are some public things
//they are method calls, and they represent functions
//that are private in here, but are made public through
//the use of this.bla = Bla;
this.publicMethod = PublicMethod;
this.otherPublicMethod = OtherPublicMethod;
//private function, made into a public method above
function PublicMethod() {
//this function/method has access to private members
//of parent function object. yay!
return m_init1;
};
//private function, made into a public method above
function OtherPublicMethod(arg) {
if(arg > 5) {
m_init2 = arg;
}
};
}
var a = new SomeClass(2, 3);
alert(a.publicMethod()); //outputs 5
the way you structure information above is a very good basis of documentation to build an oop project upon. and it sort of looks like a class i think. what i'm saying is that it seems as though your documented model would fit right into my little code example here.
I would worry less about OOP verses non-OOP than with refactoring - e.g. if you have "setBasePrice" and "setXXX" and "setYYY" that are very similar, you should convert them to a generic "setAnything()" call. OOP might help in that task but is not vital to it

Good resources for extreme minified JavaScript (js1k-style)

As I'm sure most of the JavaScripters out there are aware, there's a new, Christmas-themed js1k. I'm planning on entering this time, but I have no experience producing such minified code. Does anyone know any good resources for this kind of thing?
Google Closure Compiler is a good javascript minifier.
There is a good online tool for quick use, or you can download the tool and run it as part of a web site build process.
Edit: Added a non-exhaustive list of tricks that you can use to minify JavaScript extremely, before using a minifier:
Shorten long variable names
Use shortened references to built in variables like d=document;w=window.
Set Interval
The setInterval function can take either a function or a string. Pass in a string to reduce the number of characters used: setInterval('a--;b++',10). Note that passing in a string forces an eval invokation so it will be slower than passing in a function.
Reduce Mathematical Calculations
Example a=b+b+b can be reduced to a=3*b.
Use Scientific Notation
10000 can be expressed in scientific notation as 1E4 saving 2 bytes.
Drop leading Zeroes
0.2 = .2 saves a byte
Ternery Operator
if (a > b) {
result = x;
}
else {
result = y;
}
can be expressed as result=a>b?x:y
Drop Braces
Braces are only required for blocks of more than one statement.
Operator Precedence
Rely on operator precedence rather than adding unneeded brackets which aid code readability.
Shorten Variable Assignment
Rather than function x(){a=1,b=2;...}() pass values into the function, function x(a,b){...}(1,2)
Think outside the box
Don't automatically reach for standard ways of doing things. Rather than using d.getElementById('p') to get a reference to a DOM element, could you use b.children[4] where d=document;b=body.
Original source for above list of tricks:
http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/
Spolto is right.
Any code minifier won't do the trick alone. You need to first optimize your code and then make some dirty manual tweaks.
In addition to Spolto's list of tricks I want to encourage the use of logical operators instead of the classical if else syntax. ex:
The following code
if(condition){
exp1;
}else{
exp2;
}
is somewhat equivalent to
condition&&exp1||exp2;
Another thing to consider might be multiple variable declaration :
var a = 1;var b = 2;var c = 1;
can be rewritten as :
var a=c=1,b=2;
Spolto is also right about the braces. You should drop them. But in addition, you should know that they can be dropped even for blocks of more expressions by writing the expressions delimited by a comma(with a leading ; of course) :
if(condition){
exp1;
exp2;
exp3;
}else{
exp4;
exp5;
}
Can be rewritten as :
if(condition)exp1,exp2,exp3;
else exp4,exp5;
Although it's not much (it saves you only 1 character/block for those who are counting), it might come in handy. (By the way, the latest Google Closure Compiler does this trick too).
Another trick worth mentioning is the controversial with functionality.
If you care more about the size, then you should use this because it might reduce code size.
For example, let's consider this object method:
object.method=function(){
this.a=this.b;
this.c++;
this.d(this.e);
}
This can be rewritten as :
object.method=function(){
with(this){
a=b;
c++;
d(e);
}
}
which is in most cases signifficantly smaller.
Something that most code packers & minifiers do not do is replacing large repeating tokens in the code with smaller ones. This is a nasty hack that also requires the use of eval, but since we're in it for the space, I don't think that should be a problem. Let's say you have this code :
a=function(){/*code here*/};
b=function(){/*code here*/};
c=function(){/*code here*/};
/*...*/
z=function(){/*code here*/};
This code has many "function" keywords repeating. What if you could replace them with a single(unused) character and then evaluate the code?
Here's how I would do it :
eval('a=F(){/*codehere*/};b=F(){/*codehere*/};c=F(){/*codehere*/};/*...*/z=F(){/*codehere*/};'.replace(/function/g,'F'));
Of course the replaced token(s) can be anything since our code is reduced to an evaluated string (ex: we could've replaced =function(){ with F, thus saving even more characters).
Note that this technique must be used with caution, because you can easily screw up your code with multiple text replacements; moreover, you should use it only in cases where it helps (ex: if you only have 4 function tokens, replacing them with a smaller token and then evaluating the code might actually increase the code length :
var a = "eval(''.replace(/function/g,'F'))".length,
b = ('function'.length-'F'.length)*4;
alert("you should" + (a<b?"":" NOT") + " use this technique!");
In the following link you'll find surprisingly good tricks to minify js code for this competition:
http://www.claudiocc.com/javascript-golfing/
One example: (extracted from section Short-circuit operators):
if (p) p=q; // before
p=p&&q; // after
if (!p) p=q; // before
p=p||q; // after
Or the more essoteric Canvas context hash trick:
// before
a.beginPath
a.fillRect
a.lineTo
a.stroke
a.transform
a.arc
// after
for(Z in a)a[Z[0]+(Z[6]||Z[2])]=a[Z];
a.ba
a.fc
a.ln
a.sr
a.to
a.ac
And here is another resource link with amazingly good tricks: https://github.com/jed/140bytes/wiki/Byte-saving-techniques
First off all, just throwing your code into a minifier won't help you that much. You need to have the extreme small file size in mind when you write the code. So in part, you need to learn all the tricks yourself.
Also, when it comes to minifiers, UglifyJS is the new shooting star here, its output is smaller than GCC's and it's way faster too. And since it's written in pure JavaScript it should be trivial for you to find out what all the tricks are that it applies.
But in the end it all comes down to whether you can find an intelligent, small solution for something that's awsome.
Also:
Dean Edwards Packer
http://dean.edwards.name/packer/
Uglify JS
http://marijnhaverbeke.nl/uglifyjs
A friend wrote jscrush packer for js1k.
Keep in mind to keep as much code self-similar as possible.
My workflow for extreme packing is: closure (pretty print) -> hand optimizations, function similarity, other code similarity -> closure (whitespace only) -> jscrush.
This packs away about 25% of the data.
There's also packify, but I haven't tested that myself.
This is the only online version of #cowboy's packer script:
http://iwantaneff.in/packer/
Very handy for packing / minifying JS

Categories

Resources