From ed9f5886e8fc00ed2bdfe1ffd1e6dec432a1debe Mon Sep 17 00:00:00 2001 From: "Johannes J. Schmidt" Date: Wed, 28 May 2014 18:23:42 +0200 Subject: [PATCH] rewrite --- index.js | 70 +++++++++++++++++----------------------------------- package.json | 2 +- 2 files changed, 23 insertions(+), 49 deletions(-) diff --git a/index.js b/index.js index ad7a0d6..d3d5ec1 100644 --- a/index.js +++ b/index.js @@ -1,70 +1,44 @@ /* -* docuri +* docuri: Rich document ids for CouchDB. * * Copyright (c) 2014 null2 GmbH Berlin * Licensed under the MIT license. */ -exports.parse = function(str) { - str = str || ''; +// type/id/subtype/index/version +var PARTS = ['type', 'id', 'subtype', 'index', 'version']; - var obj = {}; - var parts = str.split('/'); - var type = parts.shift(); - var id = parts.shift(); - var subtype = parts.shift(); - var index = parts.shift(); - var version = parts.shift(); +exports.parse = function(str) { + str = str || ''; - if (type) obj.type = type; - if (id) obj.id = id; - if (subtype) obj.subtype = subtype; - if (index) obj.index = index; - if (version) obj.version = version; + return str.split('/').reduce(function(obj, value, i) { + if (value) { + obj[PARTS[i]] = value; + } - return obj; + return obj; + }, {}); }; exports.stringify = function(obj) { obj = obj || {}; - var parts = []; - if (typeof obj.type !== 'undefined') { - parts.push(obj.type); - } else { - if (obj.id || obj.subtype || obj.version || obj.index) parts.push(''); - } - - if (typeof obj.id !== 'undefined') { - parts.push(obj.id); - } else { - if (obj.subtype || obj.version || obj.index) parts.push(''); - } - - if (typeof obj.subtype !== 'undefined') { - parts.push(obj.subtype); - } else { - if (obj.version || obj.index) parts.push(''); - } - - if (typeof obj.index !== 'undefined') { - parts.push(obj.index); - } else { - if (obj.version) parts.push(''); - } - - if (typeof obj.version !== 'undefined') parts.push(obj.version); - - return parts.join('/'); + return PARTS.map(function(part) { + return typeof obj[part] === 'undefined' ? '' : obj[part]; + }).join('/').replace(/\/+$/, ''); }; exports.merge = function(str, objToMerge) { + objToMerge = objToMerge || {}; + var obj = exports.parse(str); - for (var prop in objToMerge) { - if (['type', 'id', 'subtype', 'index', 'version'].indexOf(prop) > -1) { - obj[prop] = objToMerge[prop]; + + PARTS.forEach(function(part) { + if (objToMerge[part]) { + obj[part] = objToMerge[part]; } - } + }); + return exports.stringify(obj); }; diff --git a/package.json b/package.json index b05ed61..0cfe502 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "docuri", - "version": "2.0.0", + "version": "2.0.1", "description": "Rich document ids for CouchDB", "main": "index.js", "scripts": {