Guest User

Untitled

a guest
Dec 4th, 2019
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const array = [];
  2. for (let i = 0; i < 1E7; ++i)
  3.   array.push(i);
  4.  
  5.  
  6. /* Set-based.
  7.  */
  8. const optionA = () => [...new Set(array)];
  9.  
  10.  
  11. /* Push to new array, O(1) membership tests.
  12.  */
  13. const optionB = () => {
  14.   const unique = [];
  15.   const inUnique = {};
  16.   for (let i = 0; i < array. length; ++i) {
  17.     const el = array[i];
  18.     if (inUnique[el] !== true) {
  19.       unique.push(el);
  20.       inUnique[el] = true;
  21.     }
  22.   }
  23.   return unique;
  24. };
  25.  
  26.  
  27. /* Push to new array, O(n) membership tests.
  28.  * (Will be way too slow for large, unrestricted arrays)
  29.  */
  30. const optionC = () => {
  31.   const unique = [];
  32.   for (let i = 0; i < array. length; ++i) {
  33.     const el = array[i];
  34.     if (unique.indexOf(el) === -1)
  35.       unique.push(el);
  36.   }
  37.   return unique;
  38. };
  39.  
  40.  
  41. const benchmark = f => {
  42.   console.log(f);
  43.   for (let i = 0; i < 5; ++i) {
  44.     const tPreMs = Date.now();
  45.     f();
  46.     const tSpentMs = Math.round(Date.now() - tPreMs);
  47.     console.log(tSpentMs);
  48.   }
  49.   console.log();
  50. };
  51.  
  52.  
  53. benchmark(optionA);
  54. benchmark(optionB);
  55. benchmark(optionC);
Add Comment
Please, Sign In to add comment