/**
* Removes duplicate elements from a collection (array or string) without using external libraries.
*
* @param {Array|string} collection The collection to remove duplicates from.
* @returns {Array|string} A new collection with duplicates removed, preserving the original order.
*/
function removeDuplicates(collection) {
if (!Array.isArray(collection)) {
if (typeof collection === 'string') {
// Handle string input by splitting into characters and then joining back.
return [...new Set(collection.split(""))].join("");
}
return collection; // Return as is if not array or string
}
const seen = new Set(); // Use a Set to keep track of seen elements.
const result = [];
for (let i = 0; i < collection.length; i++) {
const item = collection[i];
if (!seen.has(item)) {
seen.add(item);
result.push(item);
}
}
return result;
}
Add your comment