having fun with code

Little tricks: repeating strings in Javascript & Python

How many times have you found yourself printing strings like “————-” or “===========”? I do that a lot when I have to do console.logs or if I’m working on a console application or script. Adding dividers to the output makes it more readable.

Python has a very peculiar syntax for repeating strings, which consists in just multiplying the string by a number, like this:

  1. "123"*4 // returns "123123123123"

We can achieve the same in Javascript using Array.join() like this:

  1. Array(4).join("123"); // returns "123123123123"
  2. Array(30).join("-"); // returns "——————————"
  3. Array(2).join("<span>test</span>"); // returns "<span>test</span><span>test</span>"

Very useful for logs or to generate repeated html strings, etc.

Little tricks: concatenating arrays in Javascript

It happens that when working with Javascript frameworks like MooTools for a long time, it’s easy to forget how to do things in plain/native Javascript. For example, concatenating arrays is an easy task thanks to the Function object method apply:

  1. var array1 = [1,2,3,4];
  2. var array2 = [5,6,7];
  3. array1.push.apply(array1, array2); // array1 = [1, 2, 3, 4, 5, 6, 7]
  4. array1.push.apply(array1, [1,2,3]); // array1 = [1, 2, 3, 4, 5, 6, 7, 1, 2, 3]

Note that this method concatenates two arrays, and does not check for duplicate items.

In MooTools, the equivalent to this method would be Array.extend():

  1. var array1 = [1,2,3,4];
  2. var array2 = [5,6,7];
  3. array1.extend(array2); // array1 = [1, 2, 3, 4, 5, 6, 7]
  4. array1.extend([1,2,3]); // array1 = [1, 2, 3, 4, 5, 6, 7, 1, 2, 3]

Again, Array.extend() concatenates two arrays without checking for duplicates.

List of iPhone SDK & XCode packages

Lately I’ve been developing Android and iPhone apps with Titanium Developer and also switching from on Mac to another. At the end I ended up with a computer that only had the latest iOS 4 SDK. Thus, I couldn’t compile anymore apps for my 3G iPhone with OS 3.1.3.

Fortunately, the old versions of XCode and iPhone SDKs are still available for download, although they don’t show up in the Downloads section of the Apple Developer Connection site.

Here is a list of versions and links:
iPhone SDK 3.1 with XCode 3.2.1 for Snow Leopard (10.6.0)
iPhone SDK 3.1.3 with XCode 3.2.1 for Snow Leopard (10.6.0)
iPhone SDK 3.2 Final with Xcode 3.2.2 for Snow Leopard (10.6.0)
Xcode 3.2.3 and iPhone SDK 4 GM seed for Snow Leopard (10.6.2)
Xcode 3.2.3 and iOS SDK 4.0.1 for Snow Leopard
Xcode 3.2.3 and iOS SDK 4.0.2 for Snow Leopard

Creating QR Codes with Google Charts API

As simple as a URL: http://chart.apis.google.com/chart?cht=qr&chs=250×250&chl=http://dev.enekoalonso.com

Titanium Developer: love and hate

I’ve been using Titanium Developer for a while now, since I installed it to do some mobile app research one or two months ago. But up until now I barely used it again other than to maintain a desktop app I created for a game, which thanks to Titanium runs in both Mac and PC. Thus, up until this week, I hadn’t really get in depth with it.

The good things

Nice, easy and fast. Creating apps is piece of cake, loading JSON feeds from Internet, using local storage, placing buttons and labels on the screen… it’s all easy and it works on both iPhone and Android right away.

The bad things

Titanium Developer looks like an unfinished app. It shouldn’t be version 1.X, not even 0.X. Looks like an alpha, buggy and very easy to get screwed up, specially if you share your projects between Windows and Mac. This time it launches the emulator, this time it does not. This time your project does not load properly. Next time, you try to create a new project and it fails. And the errors are totally useless. Not very helpful.

Conclusion

The idea is great, awesome. The code is clean and using Javascript for development makes it easy for web developers to get easily involved into mobile app development. If only the Appcelerator team could improve their app, we would save a lot of headaches.

Little tricks: string padding in Javascript

I just found this little trick to zero pad numbers in Javascript. It is also applicable to padding with any character, not just zeros.

  1. var n = 123
  2. String("00000" + n).slice(-5); // returns 00123
  3. ("00000" + n).slice(-5); // returns 00123
  4. ("     " + n).slice(-5); // returns "  123" (with two spaces)

Found here.

Equivalent of parseInt() in Freemarker

Programming languages have methods to cast integers to strings and strings to integers, but usually is had to find equivalents to parseInt(), a Javascript function that basically removes all non-numeric characters from a string and returns the resulting integer.

Today, while working on a Freemarker template, I had to convert strings like “40 ms.” and “128 px” to their respective integers 40 and 128. The solution I found is to use regular expressions, which are kind of tricky in Freemarker but can save you lots of time.

Example in Javascript:

  1. console.log(parseInt("40 ms")) // outputs 40
  2. console.log("40 ms".match(/^\d+/)[0]) // outputs 40

Same in Freemarker:

  1. <#assign myInt = "40 ms."?matches("^(\\d+)(.*)")[0]?groups[1]>

Looks like even using regular expressions, in Freemarker we need to match the whole string with groups to separate the number from the rest. Thus, this will work only if the number is at the beginning of the string, which was the initial requirement in my case.

Little tricks: editing strings by index in Javascript and Python

Editing strings by index maybe something that we don’t do all the time. But it’s one of these things that, coming from languages like C, one would assume is as trivial as assigning the value of an indexed position. Something like this:

  1. var a = "hello world"
  2. a[0] = "H"
  3. console.log(a) // outputs "hello world"

Go ahead and paste that code in your favorite javascript console. You would expect the output to be “Hello there”, but it is not.
Same goes with Python, check this code:

  1. >>> a = "hello world"
  2. >>> a[0] = "H"
  3. Traceback (most recent call last):
  4.   File "<stdin>", line 1, in <module>
  5. TypeError: 'str' object does not support item assignment
  6. >>> a[0] = 'H'
  7. Traceback (most recent call last):
  8.   File "<stdin>", line 1, in <module>
  9. TypeError: 'str' object does not support item assignment

This is because strings are read only and cannot be modified at all. Only replaced with new strings.

The solution: convert to array and back to string

There may be other solutions out there, I’m sure, but this is the solution I use: Both in Python and Javascript, a string can be converted into an array or list of characters (actually, list of strings). Then we can modify values by index and finally join the output into a new string.

Javascript:

  1. var a = "hello world"
  2. a = a.split("")
  3. a[0] = "H"
  4. a = a.join("")
  5. console.log(a) // outputs "Hello world"

Python:

  1. >>> a = "hello world"
  2. >>> a = list(a)
  3. >>> a[0] = "H"
  4. >>> a = "".join(a)
  5. >>> a
  6. 'Hello world'

It’s interesting to see how the syntax for joining arrays into strings is totally the opposite in Javascript and Python. In Javascript, join() is a function of the Array object while in Python join() is a function of the string class.

In the other hand, split() is a method of the String object in Javascript. There is a split() function on the string class in Python, but it cannot be used to split strings without a specific separator. The list() function/constructor does the trick.

Change in WebSockets handshake protocol

If you are working with the latest version of Google Chrome (6.0.442.0) and you have been doing some testing or projects with WebSockets you may have already noticed there has been a change in the WebSockets specification for the client/server handshake protocol.

More info about the change:
http://webreflection.blogspot.com/2010/06/websocket-handshake-76-simplified.html
http://blog.chromium.org/2010/06/websocket-protocol-updated.html

Twitter Updates for 2010-09-30

Powered by Twitter Tools

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation