Last active
December 15, 2015 17:08
-
-
Save johnyanarella/5293749 to your computer and use it in GitHub Desktop.
toQueryString() and fromQueryString() mixins for underscore.js
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
/* | |
* Copyright (c) 2012-2013 [CodeCatalyst, LLC](http://www.codecatalyst.com/). | |
* Open source under the [MIT License](http://en.wikipedia.org/wiki/MIT_License). | |
*/ | |
require( [ 'underscore' ], function ( _ ) { | |
_.mixin( { | |
'toQueryString': function ( parameters ) { | |
var queryString = _.reduce( | |
parameters, | |
function ( components, value, key ) { | |
components.push( key + '=' + encodeURIComponent( value ) ); | |
return components; | |
}, | |
[] | |
).join( '&' ); | |
if ( queryString.length > 0 ) { | |
queryString = '?' + queryString; | |
} | |
return queryString; | |
}, | |
'fromQueryString': function ( queryString ) { | |
return _.reduce( | |
queryString.replace( '?', '' ).split( '&' ), | |
function ( parameters, parameter ) { | |
if ( parameter.length > 0 ) { | |
_.extend( parameters, _.object( [ _.map( parameter.split( '=' ), decodeURIComponent ) ] ) ); | |
} | |
return parameters; | |
}, | |
{} | |
); | |
} | |
} ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment