Skip to content

Commit

Permalink
try to guess the delimiter
Browse files Browse the repository at this point in the history
  • Loading branch information
kumo committed Oct 6, 2015
1 parent 583e59e commit 25498ab
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion mail-merge.sketchplugin/Contents/Sketch/mail-merge.sketchscript
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,48 @@ var replaceValues = function(string, values) {
return newString;
}

// based on http://stackoverflow.com/questions/19053827/csv-separator-auto-detection-in-javascript
var guessDelimiters = function(text, possibleDelimiters) {
var result = possibleDelimiters.filter(weedOut);

// make sure that we have found a delimiter, otherwise use default
if (result.length != 1) {
return /[\t,]/
} else {
return result
}

function weedOut (delimiter) {
var cache = -1;
return text.split('\n').every(checkLength);

function checkLength (line) {
if (!line) {
return true;
}

var length = line.split(delimiter).length;
if (cache < 0) {
cache = length;
}
return cache === length && length > 1;
}
}
}

var parseUserInput = function(string) {
var values = []
var rows = string.split('\n')

var separator = guessDelimiters( string, [",", ";", "\t"] )

for (var i=0; i < rows.length; i++) {
var rowText = rows[i]

if (rowText == "") {
continue
}
var rowValues = rowText.split(/[\t,;]/)
var rowValues = rowText.split(separator)

values.push(rowValues)
}
Expand Down Expand Up @@ -154,6 +185,7 @@ var onRun = function(context) {
continue
}

// change the label text
var existingText = label.stringValue()
var newText = replaceValues(existingText, rowValues);

Expand Down

0 comments on commit 25498ab

Please sign in to comment.