What's the best way to programmatically check for trailing commas in JavaScript?

Closure Compiler (Closure Tools – Google Developers) enforces this rule while minifying, so if you're also looking for a minifier, it can be a good choice.

Otherwise, it's a little bit heavyweight for the task…. JSHint (JSHint, A JavaScript Code Quality Tool) is a pretty sweet fork of JSLint[1] which is designed to be much more configurable than JSLint and runs well from the command line.

[1] Technically, I think JSHint has just been rewritten so that it is no longer dependent on the original JSLint code, but it started off as a fork and is of course still inspired by JSLint (and its inadequacies).

What is the most elegant and concise way to cast a value to a bool in JavaScript?

An important "method" that wasn't previously mentioned is that JavaScript does this implicitly wherever it can by evaluating expressions into expression references and then coercing the expression reference to a boolean for conditional evaluation. The easiest way to illustrate this is with a code example:


var foo = "bar";

if ( foo ) {
  // any code here will execute because the condition evaluated to true.
}


Here is the production from ECMA-262, Edition 5:

The production IfStatement : if ( Expression ) Statement else Statement is evaluated as follows:

  1. Let exprRef be the result of evaluating Expression.
  2. If ToBoolean(GetValue(exprRef)) is true, then
    1. Return the result of evaluating the first Statement.
  3. Else,
    1. Return the result of evaluating the second Statement.

The production IfStatement : if ( Expression ) Statement is evaluated as follows:

  1. Let exprRef be the result of evaluating Expression.
  2. If ToBoolean(GetValue(exprRef)) is false, return (normal, empty, empty).
  3. Return the result of evaluating Statement.

The important parts to note here are steps 1 & 2 from either production.

What is the ideal music to listen to while merging code conflicts?

For most quick merges, I don't have time to listen to anything.

For those painful merges from hell where you have two codebases that have diverged vastly after a long period of developing a big feature in a different branch, I've always felt that "The Roof is on Fire" is particularly appropriate.

The roof the roof the roof is on fire
The roof the roof the roof is on fire
The roof the roof the roof is on fire
We don't need no water let the motherfucker burn
Burn motherfucker burn

The parts that go "The roof is on fire repeatedly" keep the merge pressure up, and help nudge you through the tedium.

The part that goes "Burn motherfucker burn" comes to life whenever you think of the committers who checked in code that conflicts with yours ( because clearly your code is more important than their code ).

What programming language should someone learn if they've never programmed before but wanted to pursue an alternative job market?

My quip of an answer is PHP. (Browser differences with Javascript will drive you insane – don't start there. It's also object-oriented which is a whole other ball of wax I don't recommend at all, let alone for beginners. PHP is procedural and server-side, which means you can focus on programming instead of minutae.)

My real answer goes like this:

1. Programming is one of the most heavily outsourced functions around – why anyone would pursue it as a career strategy is beyond me. I am a PHP programmer (among many, many other things) and I hire other PHP programmers and I think the programming work that pays money in the US basically breaks down like this:

  • Corporate work – 90% is off-shored for cost savings. There will be some pendulum swinging against this as errors rise and quality falls and overall costs go up because it takes longer to get to quality product. However, by the time everyone really understands the financial implications of off-shoring and is willing to pay more up-front, the customization of core products will be at a point where either a) a non-programmer can get what is needed done or b) you need a very high level LAMP administrator-type (see the work being done in CMSes). Most of the jobs in this segment are for managers who talk to India in the early morning and again at night.
  • Google-type work – Unless you want to go back to college for a CS degree from a top 10 CS program and be in the 10% of your class or you're really out-of-this-world smart and want to read about programming for years to get up to speed, you're not going to qualify for these jobs.
  • Startup work – I think of this type as 24/7 live-on-caffeine work done by (young) people who taught themselves and don't necessarily have a structured or CS background. They either know too much or too little for their own good and personality (and/or geek cred) rules here.
  • General website work/freelance one-offs – This work is really more about design – especially now that WordPress and other CMSes exist. The graphics people are taking over this segment because they can offer greater customer satisfaction and charge less.
  • The segment I hire (which I think is occupied by me alone) – it boils down to people (aka men, as getting a female programmer resume just simply does not happen) with 10+ years professional experience (most of which is in a structured programming role, not freelance consulting) writing actual code because I am willing to pay for the experience level in exchange for the lack of bullshitting/babysitting.

2. What alternative job market are you trying to get into? If you want to get into a sector dominated by cross-platform work obviously you would want to choose Java. Find the job posting for the job you want and work to make your skills match it to make sure you don't go learn C++ when they need Python.

3. Programming languages tend not to work in isolation. You're at least going to need to communicate with a database in order to do anything of note so you're at least signing up to learn 2 languages. In the case of PHP I recommend pairing it with MySQL. There is also T-SQL/MS SQL and ORACLE, PostgreSQL, and many more which pair up in different combinations with programming languages.

That being said – putting alphabet soup on your resume in a big long list is just a sign that you don't know enough about any one thing to accomplish anything, so don't go overboard.

4. Start with Excel. Most people dismiss it as a Word table that can sum numbers together, but it's actually able to program some pretty complex stuff. Unfortunately, no one has written "How to Program with Excel" (that I know of). When you think of VLOOKUPs and PivotTables and "trace dependents" as the best things around you're ready to jump into PHP/MySQL.

Do JSON lists preserve ordering?

Yes. JavaScript arrays are maintained in-order, and JSON encoders/decoders maintain the order as well. "An array is an ordered collection of values."[1]

Any confusion probably arises from this: JavaScript arrays can be accessed like an object (with keys "0", "1", "2", …) and those keys are not necessarily ordered, for example, when using for(k in object) {…}. This does not impact the ordering of your array, though.

[1] http://www.json.org/

What are the most common sources of memcached cache inconsistency?

1. Application-level bugs (including bugs in previous versions of the code that didn't delete values that they changed, even if those bugs have since been fixed).

2. The following race condition.
  a. thread 1 looks at the memcache key and gets a miss
  b. thread 1 falls back to the database
  c. thread 2 changes the database value
  d. thread 2 deletes the memcache key
  e. thread 1 sets the old database value into memcache

This can be solved by using the CAS operation which tracks a version number for changes, available in recent versions of memcached.

3. Multiple versions of the code executing simultaneously, such as during a code push. If new code is being rolled out that includes the code to delete and set new cache keys, the new code might set some values which should be deleted, but the old code that's still running for the duration of the push might not delete those values if they change.

One solution to this problem is to only push the code that deletes the cache keys first, and then once that's completely finished, push the code that sets the values.

A similar problem can occur when developers are changing their code in their sandboxes and that code writes values into a memcached pool shared with other developers or production code.

4. Network problems might cause memcache clients to be unable to contact the appropriate memcached server to issue a delete. A typical behavior by memcache clients is to mark a server as "down" for some period of time after a brief network outage and ignore all operations affecting it. However, during that time, other clients might see it as up, and issue sets to data which subsequently should have been deleted by a client that sees it as down.

One solution to this is to write a log of keys that should be deleted locally and replay this log after the server comes back up. Another solution is to create a global consistent view of which memcached servers are "up" and mark a server as globally down if a client can't connect to it, and then clear all of its contents when it comes back up.

Does Facebook have rules about what languages can be used internally?

No. Our philosophy is more or less, "the right tool for the job." That said, obviously if you're working on an existing code base you'll almost always want to continue using whatever language that code is written in, since doing otherwise will mean signing yourself up for quite a lot of extra work (either rewriting the existing code or writing and maintaining an interface between it and your new stuff) and you'd have to have an extremely convincing reason. And of course, the choice of language has to take, "How many people at the company will be able to maintain this code?" into account. But in general, for any new project, you have pretty wide latitude to choose the right technology for the problem you're trying to solve.

There are significant pieces of our infrastructure written in C, C++, PHP, Java, Erlang, Ruby, and Python. Some of our developer tools are written in OCaml since it's a good language for some kinds of static analysis. And that is not an exhaustive list.

How do you avoid premature abstraction?

Don't remove duplications until you see it FOUR TIMES. If it's just two measly lines of code that is duplicated in three places, don't bother with it! Abstracting that little duplication away will not make the codebase easier to maintain. It doesn't remove a significant amount of code – in fact, there is a chance that doing this makes the code card to read. Again – wait until significant duplication actually occurs before refactoring. Another good rule of thumb is that any generalization should remove more lines of code from your project than it adds (Ironically, it's actually surprisingly often that your effort of removing duplication ends up adding more code to your project)

Refactor once your code works, NOT before. Focus on making it ugly and working first, and THEN making it pretty. Otherwise, you run the risk of getting stuck in a loop of eternal improvement. Practicing test-first makes this easier, because it makes you focus on the task at hand with the red-green-refactor cycle: Write the test (red), write code to make it pass (green) and then clean up your code (refactor). Then start writing the next test.

Intentionally create duplication when possible.
If I see that two parts of code that kind of look alike, I always intentionally make them look exactly alike. If that is possible to easily do (sometimes it is not, even though it initially looks that way) I'll break it out. This makes it much easier to spot duplication.

Python (programming language): Is there a Python equivalent to PHP's trim() function?

string.strip() is what you're looking for.

In [2]: help(''.strip)
Help on built-in function strip:

strip(…)
    S.strip([chars]) -> string or unicode
   
    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    If chars is unicode, S will be converted to unicode before stripping

Python strip differs slightly from PHP's trim in the specific whitespace characters that it will remove. PHP trim will remove null characters, while Python strip will remove '\x0c'. Both will remove '\t', '\n', '\x0b', '\r', and ' '.