Skip to content

Instantly share code, notes, and snippets.

@julietaansola
Created December 16, 2023 15:15
Show Gist options
  • Save julietaansola/01b4a59acfd36dadf8a70429242aa776 to your computer and use it in GitHub Desktop.
Save julietaansola/01b4a59acfd36dadf8a70429242aa776 to your computer and use it in GitHub Desktop.
DevOps Engineer - Rotunda Software - Julieta Ansola
function extractVariables(urlFormat, urlInstance) {
// Input validation for string types
if (typeof urlFormat !== 'string' || typeof urlInstance !== 'string') {
throw new Error('Both URLs must be strings.');
}
// Split URLs into parts
const formatParts = urlFormat.split('/');
const instanceParts = urlInstance.split('/');
// Check if the number of parts in format and instance match
if (formatParts.length !== instanceParts.length) {
throw new Error('URLs do not match.');
}
// Result object to store variable parts and their values
const result = {};
// Iterate through each part of the URLs
for (let i = 0, len = formatParts.length; i < len; i++) {
const formatPart = formatParts[i];
const instancePart = instanceParts[i];
// Check if the current part in the URL format is a variable part
if (formatPart[0] === ':') {
// This is a variable part, extract the name and value
const variableName = formatPart.slice(1);
// Check if the variable name is not empty
if (variableName) {
result[variableName] = instancePart;
} else {
// Throw an error for an invalid variable name
throw new Error('Invalid variable name in URL format.');
}
} else if (formatPart !== instancePart) {
// Throw an error if format and instance parts do not match
throw new Error('URLs do not match.');
}
}
// Handle query parameters
const queryStringStartIndex = urlInstance.indexOf('?');
if (queryStringStartIndex !== -1) {
// Extract and parse query parameters
const queryParams = urlInstance.slice(queryStringStartIndex + 1).split('&');
for (const param of queryParams) {
const [key, value] = param.split('=');
// Check if key and value are valid and add to the result object
if (key && value) {
result[key] = value;
}
}
}
return result
}
try {
const urlFormat = '/:version/api/:collection/:id';
const urlInstance = '/6/api/listings/3?sort=desc&limit=10';
const result = extractVariables(urlFormat, urlInstance);
console.log(result);
} catch (error) {
console.error(error.message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment