Skip to content

Instantly share code, notes, and snippets.

@ambar
Created October 13, 2012 07:13
Show Gist options
  • Save ambar/3883630 to your computer and use it in GitHub Desktop.
Save ambar/3883630 to your computer and use it in GitHub Desktop.
csv2vcard.js
/**
* @author ambar
* @ref http://en.wikipedia.org/wiki/VCard
*/
function parse(csv, sep) {
sep = sep || ','
var lines = csv.split('\n'), head = lines.shift().split(sep)
var json = lines.map(function(line) {
var person = {}, values = line.split(sep)
values.forEach(function(v, i) {
person[head[i]] = v
})
return person
})
return json
}
function convertPerson(person) {
var card = ['BEGIN:VCARD','VERSION:3.0']
var flag = new Flag()
Object.keys(person).forEach(function(k) {
var v = person[k], f = flag.flags[k]
if (v && f) {
var r = f.call(flag, k, v)
card.push(r)
}
})
card.push('END:VCARD')
return card.length > 3 ? card.join('\n') : ''
}
function convert(persons) {
return persons.map(convertPerson)
}
function Flag() {
this.id_ = -1
}
Flag.prototype.newId = function() {
return this.id_ += 1
}
Flag.prototype.extend = function(name, val, type) {
var id = this.newId()
return 'item' + id + '.' + type + ':' + val + '\nitem' + id + '.X-ABLabel:' + name
}
Flag.prototype.name = function(name, val) {
var id = this.newId()
return 'item' + id + '.X-ABRELATEDNAMES:' + val + '\nitem' + id + '.X-ABLabel:' + name
}
/*note 会追加,不合适*/
/*Flag.prototype.notes = function() {}*/
Flag.prototype.flags = {
'姓名' : function(k, v) {
var f = v[0], l = v.slice(1)
return 'N:' + f + ';' + l + ';;;\nFN:' + l + ' ' + f
},
'移动电话': function(k, v) {
return 'TEL;type=CELL;type=VOICE;type=pref:' + v
},
'公司邮箱': function(k, v) {
return 'EMAIL;type=INTERNET;type=WORK:' + v
},
'主要邮箱': function(k, v) {
return 'EMAIL;type=PREF,INTERNET;type=WORK:' + v
},
'Gtalk': function(k, v) {
return 'IMPP;X-SERVICE-TYPE=GoogleTalk;type=WORK;type=pref:xmpp:' + v
},
'ID': function(k, v) {
return 'NICKNAME:' + v
},
'英文名': function(k, v) {
return Flag.prototype.name.call(this, k, v)
},
'个人主页': function(k, v) {
return Flag.prototype.extend.call(this, k, v, 'URL')
},
'生日': function(k, v) {
return 'BDAY:' + v
},
'部门': function(k, v) {
return 'TITLE:' + v
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment