Permalink
Browse files

add language matching function

  • Loading branch information...
1 parent 8dab11d commit d850745c9146a5a93cf691c792344550a2d144cc @benblank benblank committed May 10, 2012
Showing with 37 additions and 1 deletion.
  1. +37 −1 src/Accept.coffee
View
38 src/Accept.coffee
@@ -128,7 +128,43 @@ getBestMatch = (candidates) ->
# Get the best language match, as per RFC 2616 section 14.4.
getBestLanguageMatch = (candidates) ->
- null
+ acceptable = ({value: candidate, q: -1, length: 0} for candidate in candidates)
+
+ for candidate in acceptable
+ value = candidate.value + "-"
+
+ for accepted, i in this
+ if (value.indexOf accepted + "-") is 0
+ length = (accepted.split "-").length
+
+ if length > candidate.length
+ candidate.q = i
+ candidate.length = length
+
+ acceptable.sort (a, b) ->
+ # Sort q = -1 to the bottom
+ if a.q is -1 and b.q isnt -1
+ return 1
+ if a.q isnt -1 and b.q is -1
+ return -1
+
+ # "q" comes from an array index, so sort 0 to the top.
+ if a.q > b.q
+ return 1
+ if a.q < b.q
+ return -1
+
+ # If all else is equal, longer matches are better.
+ if a.length < b.length
+ return 1
+ if a.length > b.length
+ return -1
+ 0
+
+ if acceptable[0].q isnt -1
+ acceptable[0].value
+ else
+ candidates[0] if "*" in this
# Get the best media-type match, as per RFC 2616 section 14.1.
getBestMediaMatch = (candidates) ->

0 comments on commit d850745

Please sign in to comment.