Created
June 24, 2011 19:17
-
-
Save deanlandolt/1045467 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Pointer(value) { | |
if (!(this instanceof Pointer)) return new Pointer(value); | |
value = value.toString().split("/"); | |
// remove a path component if all are empty | |
var empty = !value.some(function(i) { return i }); | |
if (empty) value.pop(); | |
this.path = value.map(function(part) { | |
return decodeURIComponent(part); | |
}); | |
} | |
Pointer.prototype.toString = function() { | |
// copy resolution array | |
value = this.path.map(function(i) { return i}); | |
if (!value.length) return ""; | |
// add an empty path component if all are empty | |
var empty = !value.some(function(i) { return i }); | |
if (empty) value.push(""); | |
return value.map(function(part) { | |
return encodeURIComponent(part); | |
}).join("/"); | |
}; | |
Pointer.prototype.toSource = function() { | |
return '[' + this.path.map(function(i) { | |
return '"' + i + '"'; | |
}).join('][') + ']'; | |
}; | |
Pointer.prototype.valueOf = function() { | |
return this.path; | |
}; | |
module.exports = Pointer; | |
if (require.main === module) { | |
var assert = require("assert"); | |
var pairs = [ | |
["", []], | |
["/", [""]], | |
["/a", ["","a"]], | |
["/a/", ["","a",""]], | |
["//a", ["","","a"]], | |
["//a/", ["","","a",""]], | |
["//a//", ["","","a","",""]], | |
["/a//", ["","a","",""]], | |
["/a/", ["","a",""]], | |
["//", ["",""]], | |
["///", ["","",""]], | |
["a", ["a"]], | |
["a/", ["a",""]], | |
["a/b", ["a","b"]], | |
["a/b/", ["a","b",""]], | |
["a//", ["a","",""]] | |
]; | |
pairs.forEach(function(pair) { | |
var pointer = Pointer(pair[0]); | |
assert.equal(pair[0], "" + pointer); | |
assert.deepEqual(pair[1], pointer.path); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment