|
|
| Programming Discussions about computer programming |
07-21-2012, 07:45 PM
|
#31
|
|
veteran
Join Date: Sep 2004
Posts: 2,851
|
Re: Learning Javascript Thread
Quote:
Originally Posted by Zygote
Is my code in need of a lot of improvement or is that a pretty succinct effort at the task?
|
There are a lot of improvements to be made but for a learning JS thread and 3 hours of work it's reasonable.
I would first look into your hit() and dealerHit() functions and try to re-factor that into 1 function and then pass isDealer as a parameter to handle the extra logic.
|
|
|
07-21-2012, 10:00 PM
|
#32
|
|
newbie
Join Date: Nov 2009
Posts: 40
|
Re: Learning Javascript Thread
i don't have much to say about your code as a console attempt, but you might want to have a look at this: http://google-styleguide.googlecode....criptguide.xml  .
also i whipped this up though haven't tested much. poor man's blackjack:
Code:
Array.prototype.max = function() {
return Math.max.apply({}, this);
};
Array.prototype.min = function() {
return Math.min.apply({}, this);
};
Array.prototype.count = function() {
var total = 0,
aces = 0;
for (var i = 0; i < this.length; i++) {
total += this[i];
aces += (this[i] === 1) ? 1 : 0;
}
return ((aces && total < 12) ? [total + 10, total] : [total]);
};
Array.prototype.best = function() {
if (this.length === 1) {
return this[0];
} else {
return ((this[0] > 21) ? this[1] : this.max());
}
};
var draw = function() {
var card = Math.floor(Math.random() * 13 + 1);
return ((card > 10) ? Math.max(card - 3, 10) : card);
};
var deal = function() {
var dealer = [draw(), draw()],
player = [draw(), draw()],
dtotal = dealer.count(),
ptotal = player.count(),
dbest, pbest, hit;
if (dtotal[0] === 21 && ptotal[0] === 21) {
alert('Dealer has Blackjack, but so do you!');
return;
} else if (dtotal[0] === 21) {
alert('Dealer has Blackjack! You suck!');
return;
} else if (ptotal[0] === 21) {
alert('You have Blackjack! You rule!');
return;
}
alert('Dealer shows ' + ((dealer[0] - 1) ? dealer[0] : 'Ace') + '.');
do {
hit = confirm('Your total is ' + ptotal.join(' or ') + '. Would you like to hit?');
if (hit) {
player.push(draw());
}
ptotal = player.count();
} while (hit && ptotal.min() < 22);
pbest = ptotal.best();
if (pbest > 21) {
alert('You have ' + pbest + ' and busted! You suck!');
return;
}
// Dealer hits soft 17
while (dtotal[0] < 17 || dtotal[0] === 17 && dtotal.length === 2) {
dealer.push(draw());
dtotal = dealer.count();
}
dbest = dtotal.best();
if (dbest > 21) {
alert('Dealer has ' + dbest + ' and busts! You rule!');
} else if (pbest === dbest) {
alert('Dealer has ' + dbest + '. You have ' + pbest + ' and push!');
} else if (pbest < dbest) {
alert('Dealer has ' + dbest + '. You have ' + pbest + ' and lose!');
} else if (pbest > dbest) {
alert('Dealer has ' + dbest + '. You have ' + pbest + ' and win!');
}
};
do {
deal();
} while(confirm('Play again?'));
|
|
|
07-21-2012, 11:03 PM
|
#33
|
|
newbie
Join Date: Nov 2009
Posts: 40
|
Re: Learning Javascript Thread
be nice to always see the dealer's up card...
Code:
Array.prototype.max = function() {
return Math.max.apply({}, this);
};
Array.prototype.min = function() {
return Math.min.apply({}, this);
};
Array.prototype.count = function() {
var total = 0,
aces = 0;
for (var i = 0; i < this.length; i++) {
total += this[i];
aces += (this[i] === 1) ? 1 : 0;
}
return ((aces && total < 12) ? [total + 10, total] : [total]);
};
Array.prototype.best = function() {
if (this.length === 1) {
return this[0];
} else {
return ((this[0] > 21) ? this[1] : this.max());
}
};
var draw = function() {
var card = Math.floor(Math.random() * 13 + 1);
return ((card > 10) ? Math.max(card - 3, 10) : card);
};
var deal = function() {
var dealer = [draw(), draw()],
player = [draw(), draw()],
dtotal = dealer.count(),
ptotal = player.count(),
showing = 'Dealer is showing ' + ((dealer[0] - 1) ? dealer[0] : 'Ace') + '.',
dbest, pbest, hit;
if (dtotal[0] === 21 && ptotal[0] === 21) {
return alert('Dealer has Blackjack, but so do you!');
} else if (dtotal[0] === 21) {
return alert('Dealer has Blackjack! You suck!');
} else if (ptotal[0] === 21) {
return alert('You have Blackjack! You rule!');
}
do {
hit = confirm(showing + ' Your total is ' + ptotal.join(' or ') + '. Would you like to hit?');
if (hit) { player.push(draw()); }
ptotal = player.count();
} while (hit && ptotal.min() < 22);
pbest = ptotal.best();
if (pbest > 21) { return alert('You have ' + pbest + ' and busted! You suck!'); }
// Dealer hits soft 17
while (dtotal[0] < 17 || dtotal[0] === 17 && dtotal.length === 2) {
dealer.push(draw());
dtotal = dealer.count();
}
dbest = dtotal.best();
if (dbest > 21) {
alert('Dealer has ' + dbest + ' and busts! You rule!');
} else if (pbest === dbest) {
alert('Dealer has ' + dbest + '. You have ' + pbest + ' and push!');
} else if (pbest < dbest) {
alert('Dealer has ' + dbest + '. You have ' + pbest + ' and lose!');
} else if (pbest > dbest) {
alert('Dealer has ' + dbest + '. You have ' + pbest + ' and win!');
}
};
do {
deal();
} while(confirm('Play again?'));
|
|
|
07-25-2012, 06:49 AM
|
#34
|
|
Pooh-Bah
Join Date: Jan 2005
Posts: 5,655
|
Re: Learning Javascript Thread
Quote:
Originally Posted by Shoe Lace
I would first look into your hit() and dealerHit() functions and try to re-factor that into 1 function and then pass isDealer as a parameter to handle the extra logic.
|
not really sure how i can use a parameter to achieve this. I can see a lot of close repeats in my code and im sure there is a way to condense it but dont really know what to do about it.
|
|
|
07-25-2012, 02:13 PM
|
#35
|
|
old hand
Join Date: Jul 2010
Posts: 1,211
|
Re: Learning Javascript Thread
For those new to JS, here's an excellent tool for debugging code:
http://www.jshint.com
I actually like it a little better than JSLint b/c you can set it to assume jQuery.
One other suggestion -- along with posting code in here, it can be a little easier for others to try out your code if you create a jsFiddle.
Just go to http://www.jsfiddle.net, paste in your code, and click "Save". It will create a URL that you can paste in so people can immediately try out your code.
This is a pretty cool thread idea, I'd definitely like to get involved.
|
|
|
07-27-2012, 02:25 AM
|
#36
|
|
adept
Join Date: Mar 2006
Location: San Diego
Posts: 1,105
|
Re: Learning Javascript Thread
I write CoffeeScript on a daily basis so I guess I'll chime in here.
I've had a love/hate relationship with JavaScript for much of my web development life. While it is a very expressive language with some cool features and the syntax is easy and familiar, the language has so many ****ing issues its ridiculous.
While JavaScript looks like C or Java based by it's syntax, it's actually more like Self and Scheme. It's extremely functional (functions are first-class objects) and it's object oriented implementation follows prototypal inheritance as opposed to the ever more popular classical inheritance. Lending itself to functional programming, lambdas, closures and first class functions gives you a TON of flexibility.
What I said above is actually what I like about JavaScript. It's functional nature allows you to do really neat and interesting things but as a beginner to programming you need to understand that JavaScript is not the norm. The language also has many design nightmares and I'm not even talking about all the various web browser implementations.
Some big issues with JavaScript in the tiny details that will turn into gotchas that you're trying to find for hours. A quick list off the top of my head:
- object properties are not easily iterable... you end up pulling in inherited properties from the base Object class which all JavaScript objects are born from. They also seem to follow a random order
- not instantiating all of the variables at the top of your script or code blocks (even if you aren't assigning them to anything right then and there)
- constant switching of context and the keyword "this." You have to assign "this" to another variable in order to access outer context in closures.
- easily polluting the global namespace (this becomes a huge bitch when you start writing your own or using other people's libraries if they aren't designed well)
- comparison operators and type checking are all over the place. You really need to understand how JavaScript handles object references and literals
- JavaScripts crappy object constructor (the "new" keyword) and what it actually does.
- no private properties on objects (there's a hacky kind of way of doing this, I guess).
Really when you dig into the history of JavaScript what you find are a lot of solutions to the quick list I made in various libraries and coding practices. However, these are all compromises done by people out of the necessity of having to use the language that is the lingua franca of the web.
All this said, if I were to start over JavaScript today here is what I would do:
- Take a couple free online JavaScript courses
- Buy Modern Javascript: Develop and Design by Larry Ullman (this is a great primer on client-side JavaScript for Events, DOM manipulation and Ajax)
- Buy Programming JavaScript Applications by Eric Elliott (this book is new and a work in progress but is absolutely fantastic at describing the short comings of current day JavaScript and the patterns to overcome them, its currently on chapter 5 or 6.)
- Learn CoffeeScript
That's it. Once you know the history of JavaScript and it's quirks you are safe to use CoffeeScript (or any other to-JS language of choice). It's so important to understand all the nuances of this dumb language before switching to one of them though. The reason for this is that you will get caught up in Clojure, CoffeeScript, Dart, etc. and the only way to see the bugs sometimes is to inspect the compiled JavaScript source and understand what's really going on.
You'll notice I didn't recommend Douglas Crockford's JavaScript: The Good Parts book . I find him to be a bit of an ego stroker and that book is from 2008. Not to say it isn't still relevant but JavaScript's best practices are changing almost yearly. He's also a "JavaScript purist" so his ideals are a bit extreme. I also didn't recommend The Definitive Guide as I think that reads more like a reference guide than a book to learn from.
Last edited by RICHI8; 07-27-2012 at 02:27 AM.
Reason: add lack of private properties
|
|
|
07-27-2012, 03:48 AM
|
#37
|
|
newbie
Join Date: Nov 2009
Posts: 40
|
Re: Learning Javascript Thread
Quote:
Originally Posted by RICHI8
- object properties are not easily iterable... you end up pulling in inherited properties from the base Object class which all JavaScript objects are born from. They also seem to follow a random order
- not instantiating all of the variables at the top of your script or code blocks (even if you aren't assigning them to anything right then and there)
- constant switching of context and the keyword "this." You have to assign "this" to another variable in order to access outer context in closures.
- easily polluting the global namespace (this becomes a huge bitch when you start writing your own or using other people's libraries if they aren't designed well)
- comparison operators and type checking are all over the place. You really need to understand how JavaScript handles object references and literals
- JavaScripts crappy object constructor (the "new" keyword) and what it actually does.
- no private properties on objects (there's a hacky kind of way of doing this, I guess).
|
agree with these but have gotten to the point where i've somewhat internalized the gotchas, yes object iteration/copying, how every number is a 64-bit float, ugly nested callbacks, etc. etc. once you get the hang of everything there is a certain elegance. for private members i just prefix with an underscore. i've been meaning to take up coffeescript but am already several thousand lines into my current js project.
never had much luck book learning, but i do find myself reading blogs. there's a good list here:
http://stackoverflow.com/questions/4...vascript-blogs
i will probably check out resig's javascript ninja book though.
|
|
|
07-28-2012, 02:16 AM
|
#38
|
|
adept
Join Date: Mar 2006
Location: San Diego
Posts: 1,105
|
Re: Learning Javascript Thread
There's a certain elegance to JavaScript until you start using an actually elegant language  I really do recommend checking out CoffeeScript. If you come from a Ruby or Python background it will be cake. People bitch about it being strict on indentation, but c'mon it's 2012 - if you aren't properly formatting your code it isn't the language's fault.
Its compiler takes care of 95% of those "gotchas". Some of my favorite features:
- You don't have to declare variables explicitly with the var keyword
- You can declare variables anywhere in the script and it will automatically declare them for you at the top of the respective "block" (quoted because JavaScript doesn't technically have code blocks, just scopes)
- A classical style implementation for OOP equipped with real inheritance (I do thank JavaScript for its expressiveness to allow CoffeeScript to emulate this). It's really neat, you get to write things out like classes, and they work like classes, but when it compiles it does it using the prototypal chain.
- Fat arrow functions to help lock context
- Super simple hash rocket (->) for declaring a function, so great when dealing with callbacks
- All files are automatically wrapped in an anonymous function that gets executed
- Higher level loops that actually compile to low level for loops
- unless conditional statements
- existential operator
The way I look at it is this: can I write better JavaScript than some of the very best minds in the JavaScript scene? For me it's no and when you combine that with the other awesome features it's a no brainer.
Even trivial jQuery things become expressed so much more clearly.
This:
Code:
$(document).ready(function() {
$('#some-id').click(function() {
$(this).hide();
});
)};
becomes this:
Code:
$ ->
$('#some-id').click ->
@hide()
Last edited by RICHI8; 07-28-2012 at 02:21 AM.
Reason: add code blocks to preserve formatting
|
|
|
07-28-2012, 09:43 AM
|
#39
|
|
veteran
Join Date: Sep 2004
Posts: 2,851
|
Re: Learning Javascript Thread
There's some bad stuff with coffee script too.
- If you plan to do any open source work you're instantly cutting off a huge majority of people who would use or contribute to your project. The JS that CS generates is JS in the end but it's really verbose and definitely doesn't resemble how most people would write JS by hand.
- If you ever get stuck on a problem and need to post something on stackoverflow you'll only get help by people who write CS unless you manually convert it to JS.
- Most reasonable code editors support snippets. You don't save that much time with CS. You might type -> for a function but in my editor I type "fn" and hit tab and I get the same thing.
Speaking on code editors, that's another thing too. You'll be restricted to using an editor that has proper support for CS (syntax highlighting, indention rules, possibly snippets).
- If you work locally with multiple developers they will have to use CS. If you try to get a job as a JS developer you will very restricted.
- CS really doesn't do anything except change the syntax of JS and enforce their standards. JS is tricky because there's usually a few ways to do anything, CS picks one for you and you can't opt out.
In other words, everything that CS does can be done in regular JS if you stick to using those standards. The only difference is you will be writing JS instead of some other syntax that compiles down to JS.
|
|
|
07-28-2012, 02:47 PM
|
#40
|
|
adept
Join Date: Mar 2006
Location: San Diego
Posts: 1,105
|
Re: Learning Javascript Thread
Those were great arguments against CoffeeScript early on. Syntax highlighting is available for all the popular editors. CoffeeScript incredibly wide spread now and even a lot of companies are using it over JavaScript for productivity purposes alone. You can learn CoffeeScript in a weekend if you are an intermediate (doing more than DOM manipulation and Ajax) JavaScript developer. That said, 99% of the gotchas people run into with CoffeeScript are context issues, which you're going to have in JavaScript anyway. Also interesting is that ECMAScript 6 is adopting a couple of features from CoffeeScript.
|
|
|
07-28-2012, 03:03 PM
|
#41
|
|
veteran
Join Date: Sep 2004
Posts: 2,851
|
Re: Learning Javascript Thread
I wouldn't really say it's wide spread at all tbh.
Stackoverflow tag search:
JS: 240,641 -vs- CS: 1,798 (JS+CS: 747)
That's not even close. That's less than 1% if you were to compare JS vs CS.
On a popular code distribution site like github which hosts code from any language JS is being used by 20% of the entire code base and is the #1 used language.
You can't even see the % for coffee script because it's so low. It's the 11th most popular language but to put that into perspective that's likely going to be 2-3% usage based on the 10th most popular language being 3%.
|
|
|
07-28-2012, 11:18 PM
|
#42
|
|
adept
Join Date: Mar 2006
Location: San Diego
Posts: 1,105
|
Re: Learning Javascript Thread
Oh c'mon those are lame ass metrics and I don't even need to explain why but I will if you want me to.
|
|
|
07-29-2012, 08:53 AM
|
#43
|
|
veteran
Join Date: Sep 2004
Posts: 2,851
|
Re: Learning Javascript Thread
Yeah I do want you to explain why because it's hard to disagree with github and stackoverflow's stats. Those are both extremely popular and extremely developer oriented web sites.
Here's another fun metric on raw search results from Google:
javascript: About 2,160,000,000 results
"coffee script": About 259,000 results
coffeescript: About 515,000 results
That's multiple orders of magnitudes lower.
|
|
|
07-29-2012, 11:36 AM
|
#44
|
|
grinder
Join Date: Aug 2004
Posts: 419
|
Re: Learning Javascript Thread
I'm a huge fan of Coffeescript. Those numbers appear to me as opportunity, old developers stuck where they are either out of momentum, complacency, or corporate/client dictate. Rails 3.1 is shipping with Coffeescript, and I've heard/seen several well known developers discuss it. It's just so much nicer not looking at all the clutter while trying to think.
|
|
|
07-29-2012, 12:27 PM
|
#45
|
|
adept
Join Date: Mar 2006
Location: San Diego
Posts: 1,105
|
Re: Learning Javascript Thread
Quote:
Originally Posted by Shoe Lace
Yeah I do want you to explain why because it's hard to disagree with github and stackoverflow's stats. Those are both extremely popular and extremely developer oriented web sites.
Here's another fun metric on raw search results from Google:
javascript: About 2,160,000,000 results
"coffee script": About 259,000 results
coffeescript: About 515,000 results
That's multiple orders of magnitudes lower.
|
FWIW I use both GitHub and StackOverflow. Here's why your metrics don't make sense:
- JavaScript is ~15 years old, CoffeeScript is barely two years old (in regards to your Google search)
- A lot of the JS libraries on GitHub are jQuery fart plugins and libraries dealing with the short comings of JS
- Most of the CS libraries on GitHub are to add utility to the language
- Obviously StackOverflow is going to have more JS questions than CS questions. JS has issues that a lot of JS developers get caught up on. And more importantly, the average programming skill level of JS developers is far lower than the average CS programmer.
I bet if you were to compare your metrics to only include the higher level of JS programmers, I would say the top 1% of the language because there are so many crappy JS programmers, to CoffeeScripters then your metrics would be a lot more close than you think.
|
|
|
| Thread Tools |
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
All times are GMT -4. The time now is 08:18 AM.
|