Please write a stable and fully functional Tampermonkey script that accomplishes the following task: Convert this: 6,34 mln into this: 6 340 000. Ensure that the script is compatible with the latest versions of major web browsers (e.g., Chrome, Firefox, Edge) and follows best coding practices for Tampermonkey scripts. Include detailed comments explaining each part of the code to enhance readability and maintainability. Avoid using deprecated features or methods that may lead to errors or unintended behavior.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// ==UserScript==
// @name YouTube Subscriber Count Expander
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Convert abbreviated YouTube subscriber counts to full numbers
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
/*
* Set to keep track of elements that have already been processed.
* Using WeakSet so that garbage collection can remove entries when elements are removed from the DOM.
*/
var processedElements = new WeakSet();
/*
* Function to expand abbreviated subscriber count strings to full numbers.
* Example: "6,34 mln" -> "6 340 000"
*/
function expandSubscriberCount(abbreviated) {
// Map of unit suffixes to their multipliers
// Includes common English and Polish abbreviations
var units = {
'mln': 1000000, // Polish abbreviation for million
'tys.': 1000, // Polish abbreviation for thousand
'k': 1000, // English abbreviation for thousand
'M': 1000000, // English abbreviation for million
'm': 1000000, // Sometimes 'm' is used for million
'b': 1000000000, // English 'b' for billion
'mld': 1000000000, // Polish 'mld' for billion
};
// Remove non-breaking spaces and normalize spaces
abbreviated = abbreviated.replace(/\u00A0/g, ' ').trim();
// Regular expression to extract the numeric part and unit suffix
var regex = /^([\d,\.]+)\s*([a-zA-Z\.]*)$/;
var match = abbreviated.match(regex);
if (!match) {
// If the string doesn't match the expected format, return it unchanged
return abbreviated;
}
var numberPart = match[1];
var unitPart = match[2] || '';
// Handle decimal separator and thousands separator
// Assume that if comma ',' is present, it's used as the decimal separator
if (numberPart.indexOf(',') !== -1) {
// Remove thousands separator '.' (if any)
numberPart = numberPart.replace(/\./g, '');
// Replace decimal comma ',' with period '.'
numberPart = numberPart.replace(',', '.');
} else {
// Else, remove thousands separator ',' (if any)
numberPart = numberPart.replace(/,/g, '');
}
// Get the multiplier based on the unit suffix
var multiplier = units[unitPart] || 1;
// Parse the numeric part to a float
var numberValue = parseFloat(numberPart);
if (isNaN(numberValue)) {
// If parsing fails, return the original string
return abbreviated;
}
// Calculate the full number
var fullNumber = numberValue * multiplier;
// Format the full number with appropriate thousands separators
// Using Intl.NumberFormat for locale-aware formatting
var formattedNumber = Math.round(fullNumber).toLocaleString();
return formattedNumber;
}
/*
* Function to process a single element:
* - Expands abbreviated subscriber counts in the text content and attributes
*/
function processElement(element) {
// Check if the element has already been processed
if (processedElements.has(element)) {
return;
}
// Mark the element as processed
processedElements.add(element);
// Get the current text content of the element
var abbreviatedText = element.textContent;
// Expand the abbreviated count to full number
var expandedText = expandSubscriberCount(abbreviatedText);
// Update the text content of the element
element.textContent = expandedText;
// Update the 'title' attribute if present
if (element.hasAttribute('title')) {
var titleText = element.getAttribute('title');
var expandedTitle = expandSubscriberCount(titleText);
element.setAttribute('title', expandedTitle);
}
// Update the 'aria-label' attribute if present
if (element.hasAttribute('aria-label')) {
var ariaLabel = element.getAttribute('aria-label');
var expandedAriaLabel = expandSubscriberCount(ariaLabel);
element.setAttribute('aria-label', expandedAriaLabel);
}
}
/*
* Function to process all existing elements matching the target class
*/
function processAllElements() {
// Query all elements with the specified class names
var elements = document.querySelectorAll('.yt-subscription-button-subscriber-count-branded-horizontal.yt-subscriber-count');
elements.forEach(function(element) {
processElement(element);
});
}
/*
* Create a MutationObserver to watch for changes in the DOM
* This allows the script to process elements dynamically added to the page
*/
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// Loop through the added nodes
mutation.addedNodes.forEach(function(node) {
// Only process element nodes
if (node.nodeType === Node.ELEMENT_NODE) {
// Check if the added node matches the target selector
if (node.matches('.yt-subscription-button-subscriber-count-branded-horizontal.yt-subscriber-count')) {
// Process the node
processElement(node);
} else {
// Check if any of the descendants match the target selector
var elements = node.querySelectorAll('.yt-subscription-button-subscriber-count-branded-horizontal.yt-subscriber-count');
elements.forEach(function(element) {
processElement(element);
});
}
}
});
});
});
// Start observing the document body for added child nodes and subtree modifications
observer.observe(document.body, {childList: true, subtree: true});
// Initial processing of existing elements
processAllElements();
})();
Explanation:
This Tampermonkey script converts abbreviated subscriber counts (like "6,34 mln") into full numbers (like "6 340 000"). It targets elements with the class yt-subscription-button-subscriber-count-branded-horizontal yt-subscriber-count and updates their text content, title, and aria-label attributes.
Processing Functionality: The expandSubscriberCount function handles the conversion by:
Removing any non-breaking spaces.
Extracting the numeric part and unit (e.g., "mln" for million) using a regular expression.
Handling decimal and thousands separators based on the presence of commas and periods.
Multiplying the numeric value by the appropriate factor based on the unit.
Formatting the full number with thousands separators using Intl.NumberFormat.
Dynamic Content Handling: The script uses a MutationObserver to watch for changes in the DOM and automatically process any new elements that match the target class.
Performance Optimization: A WeakSet named processedElements ensures that each element is only processed once, preventing unnecessary re-processing.
Compatibility and Best Practices:
Uses modern JavaScript features supported by the latest versions of Chrome, Firefox, and Edge.
Avoids deprecated methods.
Includes detailed comments explaining each part of the code for readability and maintainability.
To use this script:
Install the Tampermonkey extension in your browser.
Create a new script and paste this code into it.
Save the script and refresh YouTube or the target website.
The subscriber counts should now display full numbers instead of abbreviations.