Skip to content

Instantly share code, notes, and snippets.

@pmuellr
Created August 16, 2011 13:55
Show Gist options
  • Select an option

  • Save pmuellr/1149137 to your computer and use it in GitHub Desktop.

Select an option

Save pmuellr/1149137 to your computer and use it in GitHub Desktop.
function and test case to split a string by commas
#!/usr/bin/env node
function splitByComma(string) {
string = string.replace(/^\s*/,"")
string = string.replace(/\s*$/,"")
var result = string.split(/\s*,\s*/)
if (result.length == 1) {
if (result[0] == "") {
return []
}
}
return result
}
failures = 0
function test(a, b, message) {
original_b = b
b = splitByComma(b)
// console.log("splitByComma('" + original_b + "'): ", b)
if (a.length != b.length) {
console.log("fail because lengths different: " + message)
failures++
return
}
for (var i=0; i<a.length; i++) {
if (a[i] != b[i]) {
console.log("fail because element at index " + i + " different: " + message)
failures++
return
}
}
}
test([], "", "empty string")
test([], " ", "space")
test([], " ", "spaces")
test([], "\t\t\t", "tabs")
test(["a"], "a", "a")
test(["a", ""], "a,", "a, empty")
test(["", "a"], ",a", "empty, a")
test(["a"], "\ta\t\t", "spaces a")
test(["a", "b"], "a,b", "a,b")
test(["a", "b"], " a , b ", "spaces a,b")
test(["a", "", "b"], " a , , b ", "spaces a,empty,b")
test(["a", "", "b"], " a ,, b ", "spaces a,skinny empty,b")
test(["a", "b"], "a , b", "inner spaces a,b")
test(["a12", "b34", "c56"], " a12 , b34,c56", "spaces a12,b34,c56")
if (failures == 0) {
console.log("all tests pass")
}
else {
console.log("failed tests: " + failures)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment