Skip to content

Instantly share code, notes, and snippets.

@toastal
Last active October 18, 2021 08:08
Show Gist options
  • Save toastal/b51a3d42ccc971e0c05e to your computer and use it in GitHub Desktop.
Save toastal/b51a3d42ccc971e0c05e to your computer and use it in GitHub Desktop.
Object to Query String Refactors
// Well the string building is pretty dopey with the `+=` append on
// a forEach instead of a map, but that slice on the last char sends
// shivers of cringe up my spine.
_.mixin({
param: function(obj) {
var param = "";
_.forEach(obj, function(val, key) {
param += key + "=" + val + "&";
});
return param.slice(0, -1);
}
});
_.param({test: "foo", me: 1});
//=> "test=foo&me=1"
// Reasons to favor currying+composition/piping below--one liner, clean.
// This is why I tell people Ramda > lodash in 'functional' JS land.
//
// R.pipe is like the "|>" operator in a lot of other languages. In this
// expample its similar to this, but the curried pipeline part:
// obj
// |> toPairs
// |> map << join "="
// |> join "&"
// objToQueryStr : Object -> String
const objToQueryStr = R.pipe(R.toPairs, R.map(R.join("=")), R.join("&"));
// could be vaguely cleaner with destructuring to get all those "R." out
// of the way too
// const {join, map, pipe, toPairs} = R;
// const objToQueryStr = pipe(toPairs, map(join("=")), join("&"))
objToQueryStr({test: "foo", me: 1});
//=> "test=foo&me=1"
// Jesus christ lodash
// Shooting for point-free requires both a join function since lodash
// doesn't provide one (and it seems there's no sensible way to
// `_.partial(Array.prototype.join, _, "")`) and an ugly mess of
// partials because of 'wrong' argument order. `flow` works like
// `R.pipe` in Ramda.
_.mixin({
join: function join(array, string) {
var string = string || ",";
return array.join(string);
},
param: _.flow(_.pairs, _.partial(_.map, _, _.partial(_.join, _, "=")), _.partial(_.join, _, "&"))
});
_.param({test: "foo", me: 1});
//=> "test=foo&me=1"
// I guess we'll try chaining... nope, gross
_.mixin({
param: function param(obj) {
return _.chain(obj).pairs().map(function(a) {
return a.join("=");
}).join("&").value();
}
});
_.param({test: "foo", me: 1});
//=> "test=foo&me=1"
// Fine, I give up on pretty piping/composition... map + join
_.mixin({
param: function param(obj) {
return _.map(obj, function(value, key) {
return key + "=" + value;
}).join("&");
}
});
_.param({test: "foo", me: 1});
//=> "test=foo&me=1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment