How to write X in both Python 3 and JavaScript 178 points by chibicode on Sept 14, 2018 | hide | past | web | favorite | 78 comments

 Sort example doesn't take into account Javascript does lexicographical sorting?javascript:`````` someList = [ 40, 2, 1, 3, 7, 99] someList.sort() Array(6) [ 1, 2, 3, 40, 7, 99 ] `````` python:`````` someList = [ 40, 2, 1, 3, 7, 99] sorted(someList) [1, 2, 3, 7, 40, 99]``````
 Your comment led me to discover https://www.reddit.com/r/softwaregore and reaffirm myself that I should stay away from javascript for as long as I can
 It depends on whether or not you pass it a basic comparator function, eg:`````` someArray.sort((a,b) => a - b); `````` But yeah the example would have needed this for the less complex example as well to be accurate.
 Common mistake when writing a sorting function, a-b is not safe in languages with integer overflow because it will give you incorrect sorting for large numbers. In javascript where everything is double you're probably safe from that kind of error but maybe NaN can give you problems instead?
 Too true.‘a-b’ is safe enough in JS if you always know the input will be within a safe range regarding integer sizes and types.NaN can give you all kinds of trouble so I’d usually test for that in a real case, either before the sort or in the comparator—if necessary.
 Shouldn't that be `a < b`?
 No, the compare function needs to be able to indicate when two values are equal, not just when one is smaller/larger than the other. Otherwise your sort function will return inconsistent results for compare(a, b) and compare(b, a) when both values are equal.
 So`````` someList.sort((a,b) => a => b) `````` Would be better, because it produces a stable sort?`a - b` produces the same results, so equally valid?
 (I'm assuming you meant "a >= b", not "a => b".)That's still not a consistent comparison function, so the results are implementation-defined.To be consistent, it's required, among others, that if cmp(a, b) == 0 then cmp(b, a) == 0. For "a >= b", this is not always true, e.g.:`````` » cmp(0, 1) == 0 true » cmp(1, 0) == 0 false``````
 No. `(a,b) => a => b` cannot produce a stable sort in all scenarios. Would theoretically work fine for integers since there's no difference between any two instances of the same number, but consider:`````` let arr = [ {number: 2, name: 'a'}, {number: 1, name: 'b'}, {number: 1, name: 'c'}, ] `````` Now assume we want to sort arr with a compare function, and our sort function expects the compare function to return a boolean, not an integer.`````` let compare = (a,b) => a.number => b.number compare(arr[0], arr[1]) //=> true, so the object named 'a' comes after 'b' compare(arr[1], arr[2]) //=> true, so the object named 'b' comes after 'c'? `````` See the problem?
 That will give you a sequence of decreasing numbers. `a-b` will work just as `a > b`.If `a-b` returns a negative number, the result will be treated as -1. If the numbers are the same, then you end up with 0, and so on.I don't know what's faster in that case.
 a > b is not a consistent comparison function. The behavior of sort() with such a function is implementation-defined.
 Agreed. I wouldn't use it the way shown here. I would make sure to return a hard negative, zero, or one in any case.I was surprised when I read into how many different ways `Array.prototype.sort()` is implemented across environments.
 Oh gosh. TIL.Edit: I'm actually truly grateful, I'm sure this bit of knowledge saved me some of my hair in the future.
 To me this seems like a bug, or at best an incomplete implementation. Let's fix it in the next version of JavaScript, okay? I suppose someone's code will break, but was it worth preserving?
 That's a good point. Although there is another sorting example which is using the correct format. But yes, you are indeed right.
 I swear this language gets worse every time I learn something new about it.
 As someone who is often switching languages, I find these sorts of cheatsheets useful.I know all the syntax in them but I'll be damned if I can ever remember which language uses which until I've settled back in to things.
 My go-to site is usually https://learnxinyminutes.com/
 Me too. On any given day, I can be using any of a half dozen languages (C#, powershell, javascript, bash, perl, python, c++, java - our codebase is all over the place). It gets hard to keep the syntax straight on all of them.
 You might find Rosetta Code to be useful - it's a wiki site with hundreds of examples, all with solutions in dozens of languages for comparison.ikewise, I felt a little let down. On the flipside, it's an excellent opportunity to bring Rosetta Code to people's attention - a wiki with hundreds of example problems, each solved in many languages for comparison!https://www.rosettacode.org/wiki/Rosetta_CodeI find it invaluable in that sort of mid-learning level of a new language, where I have the syntax sorted, but I need lots of programs small enough to hold in my head, but also large enough to show off all the features, to learn and read. Here's Dijkstra, for example: https://www.rosettacode.org/wiki/Dijkstra%27s_algorithm
 How to write using X in both languages:
 A couple more native X11 client implementations:Common Lisp: https://github.com/sharplispers/clxAny others?(Looking for implementations of the X11 protocol in \$LANGUAGE, not bindings to the C Xlib)
 One more that I use:Emacs Lisp: https://github.com/ch11ng/xelb
 This is what I actually thought the article was going to be about!
 Haha, I also expected this.Now I'm kind of glad you responded in kind because I'd seen python-xlib but not the node one. That sounds like a bit of fun and punishment at the same time.
 At least I wasn't the only one lol
 This what I expected from the title.
 When I read the headline I was expecting the X windowing system. When I clicked the article and saw “junior programmer” I thought this is about to be impressive.Cool site :P
 Very cool! Reminds me of http://youmightnotneedjquery.com/I particularly enjoyed seeing that you used snake case in Python and camel case in JavaScript. Great attention to detail.
 Creator here! Let me know if you have any suggestions.
 Truthiness!Although this is a case where idiomatic python is different from idiomatic js.In js:`````` // same: !! "" // false !! 0 // false !! 1 // true !! null // false // different: !! {} // true !! [] // true `````` while in python:`````` # same: not not "" # False not not 0 # False not not 1 # True not not None # False # different: not not {} # False not not [] # False not not tuple() # False``````
 Nice list.Perhabs just personal preference but I'd use`````` for(let element of someList){ console.log(element); } `````` instead of`````` someList.forEach(element => { console.log(element) }) `````` for...of is easier to read and recognize as a loop construct at first glance, and as far as I recall it's also faster nowadays since the body of the loop is inline, whereas forEach requires the runtime to deal with a function object.
 Personally I find the method-style syntax significantly more readable.
 You can also ‘return’ the outer function from within a ‘for...of’ which is pretty useful imo.
 And you can use await in the context of an outer async function, which is a huge advantage in reducing code complexity.
 Makes me wonder if maybe the syntax for mapping, folding and other collection operations should have a similar syntax to for instead of the current method-style syntax popular in most modern languages.
 C# has a syntax called Linq Query Syntax that provides keywords in the language to do things like map, filter, and reduce.Example:`````` var queryLondonCustomers = from cust in customers where cust.City == "London" select cust; `````` I'm not a big fan of it honestly, the function style seems more consistent and easier to read to me.
 https://www.pyret.org/ does it like this:`````` for each(str from [list: "Ahoy", "world!"]): print(str) end for map(n from [list: 1,2,3]): n * n end # ==> [list: 1, 4, 9] for filter(n from [list: 1, 2, 3]): n >= 2 end # ==> [list: 2, 3] for fold(sum from 0, n from [list: 4, 5, 6]): sum + n end # ==> 15``````
 That sounds a lot like Python list comprehensions
 I genuinely love the design of the page. It has personality without compromising readability. This is something a lot of people struggle to get right.
 Instead of...`````` Object.entries(newDict).forEach(element => { console.log(`\${element[0]} \${element[1]}`) }) `````` ... you could write ...`````` for (const key in newDict) { console.log(`\${key} \${newDict[key]}`) } `````` ... or ...`````` for (const [key, value] of Object.entries(newDict)) { console.log(`\${key} \${value}`) }``````
 It would be nice to have a sectioin with things that work differently in both languages. For example in python `if []:` evaluates to False while in javascript `if ([]) {` evaluates to True.
 First: congratulations, this is very well done.Second: I don't like seeing JavaScript code without semicolons. Maybe I am old, but it makes me nervous.
 Thanks for the site! Do you have thoughts on removing all the print/console.logs calls on every line? It feels like there's a lot of visual noise there, that can still be met with the comments showing state/output.
 I might suggest replacing javascript's parseInt() with Number()
 Consider renaming to "How to write \$X in both Python 3 and JavaScript" to avoid the confusion with X11 that others have pointed out? Nice article!
 I really like the page. I really enjoyed going through the list. One suggestion would be to add python/javascript generator functions to the list.
 Very cool reference.
 Add Python 2 and or another language that has a static type system like C.
 I think anyone who hasn't learned to do X in Python already really should be better off learning it in Python 3 rather than a version of the language which is in the process of deprecation.
 Either you forgot to mention that this is a personal todo, or you're trolling the author?
 http://hyperpolyglot.org/ is a great website with a similar idea.
 https://learnxinyminutes.com/ is another website with a similar aim.
 I quite like this as super thin intro. So far I always fonud it motivating enough to jump into deeper articles/books.
 No mention of http://rosettacode.org, tsk tsk. (specifically: http://rosettacode.org/wiki/Category:Programming_Tasks)
 Hehe, I didn't know that but the page reminded me of of the Arch Linux Rosetta Stone page[1] instantly ;-)
 A weird reference imo. Perhaps useful to build as a learning experience but I wouldn't expect who needs if/else included in a cheat sheet to be ready to learn to languages.
 The value is in finding what is the most idiomatic way to do something in either language. For example if you're coming from Python and you're used to sum() it is useful to check this reference for the most idiomatic way to do it in JavaScript before doing it by hand with anonymous functions and reduce or looping through the list (as is the case unfortunately).
 Agreed. The value isn’t in it being a tutorial, it’s in it being a quick overview of a language’s idioms as they apply to common tasks.
 Do people actually use cheat sheets like this? IMO, the first stackoverflow result in google is generally what I'm looking for and quicker - especially for common things and common languages such as the things on this page. Even if you have the page bookmarked, you still need to find/search/scroll for the specific thing you're looking for. Also, with Alfred you can google anything even quicker by not having to cmd+tab to the browser.
 Maybe not as a reference, but it's certainly helpful to browse if you're going from one language to another (I know python and I'm learning Javascript, this probably saved me a few google searches)
 In the past I've enjoyed using cheatsheets to get a quick feel for the syntax of a language. It's nice to see a less familiar language next to a more familiar one.
 I used a resource similar to this to get started with Javascript almost a decade ago. Reading through the examples start to finish is a decent intro to the basics.
 Reminds me of this OneLang HN post from several months ago - https://news.ycombinator.com/item?id=16415051It's an IDE that lets you code simultaneously in several different languages https://ide.onelang.io/
 Reminds me of PLEAC - Perl Cookbook translated to >10 langs http://pleac.sourceforge.net
 When I publish code about algorithms and data structures to my web site, I usually offer multiple language versions. Why? Because understanding the computer science theory and math proofs is a big effort. Writing and debugging my first implementation in any language is a big effort. But porting that code to a bunch of languages is comparatively easy and is almost a thoughtless mechanical process.
 I thought this was going to be a polyglot[1] demonstration of writing code for X Windows. However, I was not disappointed in what I found!
 I expected a Python/JS polyglot :)
 Impressive to see almost all JS examples being as short as the python ones. Python is normally valued for being short and concise but modern JS is really catching up here.
 I had such high hopes when I opened the arsenal. I anticipated it would an article of how to write code that's both JavaScript and Python syntactically correct.
 What's the point of having print or console.log around everything? Just have one box with "print to standard output" and those two at the top.
 I love it! Reminds me of https://www.interviewbit.com
 Excellent educational tool - will be passing this around to colleagues who need it. Thanks!
 Same here!
 this is very good. i had it in my head that there was no "extend" function in JS, and didn't realize "push(...array)" was possible. thank you for the super detailed guide
 FizzBuzz example isn't correct
 I was expecting to see a leftpad comparison too :D

Search: