emadalam / atvjs

Blazing fast Apple TV application development using pure JavaScript
https://emadalam.github.io/atvjs
MIT License
311 stars 49 forks source link

resolve parameters in Page.url #19

Open emadalam opened 7 years ago

emadalam commented 7 years ago

From one of the PRs https://github.com/emadalam/atvjs/pull/12

This allows to build URLs for pages dynamically based on the options.urlParams that are handed over to the page. Uses the same node-module that express uses, so the very same syntax applies. For example use “http://httpbin.org/get?test=:test” with options = {urlParams: {test: true}} to get “http://httpbin.org/get?test=true”.

Handy code snippet

function toQueryString(obj) {
    return (
        _.map(obj, (v, k) => {
            if (_.isArray(v)) {
                return (_.map(v, (av) => `${k}[]=${av}`)).join('&');
            } else {
                return `${encodeURIComponent(k)}=${encodeURIComponent(v)}`;
            }
        })
    ).join('&');
}

function toUrl(url = '', params = {}) {
    let q = toQueryString(params);
    let urlBuffer = [url];
    if (q) {
        urlBuffer.push(/\?.+$/.test(url) ? `&${q}` : `?${q}`);
    }
    return urlBuffer.join('');
}
iamrahulrnair commented 2 years ago
function toQueryString(obj) { 
   return _.map(obj, (v, k) => { 
  if (_.isArray(v)) { 
return _.map(v, (av) =>${k}[]=${av}).join('&'); 
} else { return 
   ${encodeURIComponent(k)}=${encodeURIComponent(v)}`;
    }
  }).join('&');
}

function toUrl(url = '', params = { } ) {
let q = toQueryString(params);
let urlBuffer = url;

if (q) {
urlBuffer += '?' + q;
   }
  return urlBuffer;
 }

This felt like an easy fix to get rid of reg-exp, if am wrong care to specify why the reg-exp needed in the first place?