1. /**
  2. * Removes duplicate elements from a collection (array or string) without using external libraries.
  3. *
  4. * @param {Array|string} collection The collection to remove duplicates from.
  5. * @returns {Array|string} A new collection with duplicates removed, preserving the original order.
  6. */
  7. function removeDuplicates(collection) {
  8. if (!Array.isArray(collection)) {
  9. if (typeof collection === 'string') {
  10. // Handle string input by splitting into characters and then joining back.
  11. return [...new Set(collection.split(""))].join("");
  12. }
  13. return collection; // Return as is if not array or string
  14. }
  15. const seen = new Set(); // Use a Set to keep track of seen elements.
  16. const result = [];
  17. for (let i = 0; i < collection.length; i++) {
  18. const item = collection[i];
  19. if (!seen.has(item)) {
  20. seen.add(item);
  21. result.push(item);
  22. }
  23. }
  24. return result;
  25. }

Add your comment