I have this function which is pretty easy to read and works just fine. I'm looking to advance my coding abilities by writing more concise code, though.
Does anyone know of an elegant way to condense this down? Any pointers very much appreciated! Thank you!
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
function create_filter_input($name, $termname) {
var $input = '<input class="query-input" type="hidden" value="' + $termname + '" name="' + $name + '" />';
return $input;
}
area = $_GET["area"],
type = $_GET["property_type"],
style = $_GET["style"],
feature = $_GET["feature"],
if(area || type || style || feature) {
if(area) {
areainput = create_filter_input('area',area);
$filterTerms.append(areainput);
}
if(type) {
typeinput = create_filter_input('property_type',type);
$filterTerms.append(typeinput);
}
if(style) {
styleinput = create_filter_input('style',style);
$filterTerms.append(styleinput);
}
if(feature) {
featureinput = create_filter_input('feature',feature);
$filterTerms.append(featureinput);
}
}
This is my current solution based on your answers! I think it's pretty concise. Let me know what you think! thanks again.
function create_filter_input($name, $termname, $filterterms) {
if($termname) {
var $input = '<input class="query-input" type="hidden" value="' + $termname + '" name="' + $name + '" />';
$filterterms.append($input);
}
}
create_filter_input('area',area,$filterTerms);
create_filter_input('property_type',type,$filterTerms);
create_filter_input('style',style,$filterTerms);
create_filter_input('feature',feature,$filterTerms);
$_GET[]
, PHP? but you also have variables with no$
, JS? \$\endgroup\$$
in variable names in javascript - the symbol was originally intended for machine use. Yes, I know libraries love it, but that's just one more reason not to use it - confusion with library code. \$\endgroup\$$filterTerms
- it is present in the scope in which the function was declared, so the function has access to it, even when it is not passed. \$\endgroup\$