+++ to secure your transactions use the Bitcoin Mixer Service +++

 

Skip to content

Instantly share code, notes, and snippets.

@joshleaves
Created April 3, 2013 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshleaves/5300047 to your computer and use it in GitHub Desktop.
Save joshleaves/5300047 to your computer and use it in GitHub Desktop.

Revisions

  1. joshleaves created this gist Apr 3, 2013.
    58 changes: 58 additions & 0 deletions js-6901.js
    @@ -0,0 +1,58 @@
    /*
    // Will only throw on missing leading '/'
    */
    JSON.pointer = function (object, pointer) {
    if ('undefined' === typeof object || 'undefined' === typeof pointer || '/' === pointer) {
    return object;
    }
    if ('/' !== pointer.substr(0, 1)) {
    throw new SyntaxError('Unexpected character ' + pointer.substr(0, 1));
    }
    var _path = pointer.substr(1).split('/').map(function (p, idx) {
    if (/^[0-9]$/.test(p)) {
    return parseInt(p);
    }
    return p.replace('~1', '/').replace('~0', '~');
    });

    var _object = object;
    while (_path.length) {
    _object = _object[_path.shift()];
    if ('undefined' === typeof _object) return _object;
    }
    return _object;
    };
    /*
    // Extending native objects prototypes is bâaad, m'kay?
    */
    Object.prototype.pointer = function (pointer) {
    return JSON.pointer(this, pointer);
    }


    /*
    // Quick test value. Complex enough?
    */
    var a = { foo: { bar: [ { hello: { world: true } } ] } };

    /*
    // Let's trigger an error!
    */
    try {
    // Invalid: Missing leading '/'
    console.log(a.pointer('foo'));
    } catch (e) {
    // [SyntaxError: Unexpected character f]
    console.log(e);
    }

    /*
    // Now for some real use!
    */
    console.log(a.pointer());
    console.log(a.pointer('/'));
    console.log(a.pointer('/foo'));
    console.log(a.pointer('/foo/bar'));
    console.log(a.pointer('/foo/bar/0'));
    console.log(a.pointer('/foo/bar/0/hello'));
    console.log(a.pointer('/foo/bar/0/hello/world'));