Skip to content

Improve the JavaScript syntax in the listing.html page #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
1 task done
mundume opened this issue Feb 23, 2023 · 3 comments · Fixed by #300
Closed
1 task done

Improve the JavaScript syntax in the listing.html page #17

mundume opened this issue Feb 23, 2023 · 3 comments · Fixed by #300
Assignees
Labels
💻 aspect: code Concerns the software code in the repository ✨ goal: improvement Improvement to an existing feature 🟩 priority: low Low priority and doesn't need to be rushed 🧹 status: ticket work required Needs more details before it can be worked on

Comments

@mundume
Copy link

mundume commented Feb 23, 2023

Description

Improving the JavaScript syntax to a more readable one

Alternatives

I actually modified all the three functions to use a much modern javascript syntax

here is the old code for getting url params ie getUrlVals()

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

here is the new implementation of the getUrlVals() using modern syntax

function getUrlVars() {
	const vars = {};
	const queryString = window.location.search.substring(1);
	const params = new URLSearchParams(queryString);
	for (const [key, value] of params) {
		vars[key] = value
	}
	return vars
}

Additional context

I think the modern syntax enhances a much smoother experience.
I've updated two more functions ie func updateQueryString() & removeQueryString()

Implementation

here:

  • I would be interested in implementing this feature.
@mundume mundume added ✨ goal: improvement Improvement to an existing feature 💻 aspect: code Concerns the software code in the repository 🚦 status: awaiting triage Has not been triaged & therefore, not ready for work 🟩 priority: low Low priority and doesn't need to be rushed labels Feb 23, 2023
@possumbilities possumbilities added 🧹 status: ticket work required Needs more details before it can be worked on and removed 🚦 status: awaiting triage Has not been triaged & therefore, not ready for work labels Mar 1, 2023
@possumbilities
Copy link
Contributor

@nzaih1999 Hi! thank you for bringing up this topic ❤️

Can you rewrite your Issue to address what is wrong, what should be altered, and why, rather than describing what you've already done within a PR.

Issues are generally for documenting an existing problem or new feature clearly. When that's settled, they move to a status of ready for work, from there they're free to have PRs submitted against that resolve the Issue fully.

I feel like there's not enough explanation here as to what it is that you are trying to resolve and what the benefits are. The framing you've used seems to be about what you've done, not necessarily what you are proposing yourself or anyone attempting to resolve this Issue should do.

I suggest you read the Contribution Guidelines for more details

I'm gonna leave this Issue open for a while, and move it to ticket work required.

@digi-booster
Copy link

digi-booster commented Apr 1, 2023

Hi @possumbilities, @nzaih1999 might want to refactor the code with the latest specification here

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
// from LOC(Line of Code) 69
var topic = getUrlVars()["topic"];
var language = getUrlVars()["language"];
var medium = getUrlVars()["medium"];

We can use const instead of var for variable declarations. Also we can use the URLSearchParams API to extract the query parameters and use a for...of loop and destructuring assignment to iterate through the parameters and extract their key-value pairs.

By using an object to store the query parameters, we can simplify the code and make it more readable. We can also return the object at the end of the function to improve the function's performance.

Finally, we can use object destructuring to assign the topic, language, and medium variables to their corresponding values returned by the getQueryParams function.

This code is simple, easy to read and understand, optimized for performance, and secure, as we use the latest built-in features of ES2022 and the URLSearchParams API, which is a secure and standardized way to extract query parameters from a URL.

const getQueryParams = () => {
  const params = new URLSearchParams(window.location.search);
  const queryParams = {};
  for (const [key, value] of params) {
    queryParams[key] = value;
  }
  return queryParams;
};

const { topic, language, medium } = getQueryParams();
Code In Detail
  • const getQueryParams = () => {...} defines a function getQueryParams that uses an arrow function syntax. This function is responsible for extracting the query parameters from the current URL.

  • const params = new URLSearchParams(window.location.search); creates a new instance of the URLSearchParams object, which is initialized with the search portion of the current URL.

  • const queryParams = {}; creates an empty object queryParams which will store the extracted query parameters.

  • for (const [key, value] of params) {...} uses a for...of loop to iterate over the params object. The for...of loop iterates over each key-value pair in the params object, using destructuring assignment to extract the key-value pairs into key and value variables.

  • queryParams[key] = value; sets the value of value to the corresponding key in queryParams. This creates a new key-value pair in queryParams object for each query parameter.

  • return queryParams; returns the queryParams object, which contains all the query parameters extracted from the URL.

  • const { topic, language, medium } = getQueryParams(); uses destructuring assignment to assign the values of topic, language, and medium variables to the corresponding values extracted from the query parameters using the getQueryParams function.

This code is written using the latest built-in features of ES2022 and the URLSearchParams API, which is a secure and standardized way to extract query parameters from a URL. It is optimized for performance and uses a simple and easy-to-understand approach to extract query parameters.

@digi-booster
Copy link

digi-booster commented Apr 1, 2023

Can anyone share their thoughts on the below code?

const getQueryParams = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const params = Object.fromEntries(urlParams.entries());
  return params;
};

const { topic, language, medium } = getQueryParams();

if (!topic && !medium && !language) {
  document.write("<style>.thumbnailbox { display: block; }</style>");
} else {
  let style = "";
  if (topic) style += `.${topic},`;
  if (medium) style += `.${medium},`;
  if (language) style += `.${language},`;
  style = style.slice(0, -1); // Remove last comma
  style += " { display: block; }";
  document.write(`<style>${style}</style>`);
}

let navTopicClass = topic ? ".resourcenavtopicknown" : ".resourcenavtopicunknown";
let navMediumClass = medium ? ".resourcenavmediumknown" : ".resourcenavmediumunknown";
let navLanguageClass = language ? ".resourcenavlanguageknown" : ".resourcenavlanguageunknown";
document.write(`<style>${navTopicClass}, ${navMediumClass}, ${navLanguageClass} { display: block; }</style>`);
const params = new URLSearchParams(window.location.search);
const selectors = ['topic', 'language', 'medium'].map(param => params.get(param)).filter(Boolean).join(', ');

document.write(`<style>${selectors ? `.${selectors} { display: block; }` : '.thumbnailbox { display: block; }'}</style>`);
document.write(`<style>.resourcenavtopic${topic ? 'known' : 'unknown'}, .resourcenavmedium${medium ? 'known' : 'unknown'}, .resourcenavlanguage${language ? 'known' : 'unknown'} { display: block; }</style>`);

Backward Compatible

// Get URL parameters using URLSearchParams
const params = new URLSearchParams(window.location.search);
// Get values for the topic, language, and medium parameters
const topic = params.get('topic');
const language = params.get('language');
const medium = params.get('medium');
// Combine non-empty parameters into a comma-separated string
const selectors = [topic, language, medium].filter(Boolean).join(', ');

// Construct the first style string based on the selectors string
const style1 = selectors ? `.${selectors} { display: block; }` : '.thumbnailbox { display: block; }';
// Construct the second style string based on the presence of topic, medium, and language
const style2 = `.resourcenavtopic${topic ? 'known' : 'unknown'}, .resourcenavmedium${medium ? 'known' : 'unknown'}, .resourcenavlanguage${language ? 'known' : 'unknown'} { display: block; }`;

// Write the style strings to the document using document.write()
document.write(`<style>${style1}</style>`);
document.write(`<style>${style2}</style>`);

@TimidRobot TimidRobot changed the title Improve the javascript syntax in the listing.html page Improve the JavaScript syntax in the listing.html page Apr 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
💻 aspect: code Concerns the software code in the repository ✨ goal: improvement Improvement to an existing feature 🟩 priority: low Low priority and doesn't need to be rushed 🧹 status: ticket work required Needs more details before it can be worked on
Projects
None yet
4 participants