king_of_hobbies

String replace comparison

Nov 29th, 2022 (edited)
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.24 KB | Source Code | 0 0
  1. function timeIt(f) {
  2.   const t0 = Date.now()
  3.   const r = f()
  4.   const t1 = Date.now()
  5.   return t1-t0
  6. }
  7.  
  8. function randomString(length) {
  9.   let str = '';
  10.   const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890. '
  11.   for(i = 0; i < length; i++) {
  12.     const c = Math.floor(Math.random() * chars.length)
  13.     str += chars[c]
  14.   }
  15.   return str
  16. }
  17.  
  18. function replaceRegex(str) {
  19.   return str.replace(/[aeiou]/gi, '')
  20. }
  21.  
  22. function replace(str) {
  23.   const vowels = ['a','e','i','o','u','A','E','I','O','U']
  24.   let newStr = '';
  25.   for(i = 0; i < str.length; i++) {
  26.     let c = str.charAt(i)
  27.     if (vowels.indexOf(c) === -1) {
  28.       newStr += c
  29.     }
  30.   }
  31.   return newStr
  32. }
  33.  
  34. function iterate(count, length, f) {
  35.   let time = 0
  36.   for(let i = 0; i < count; i++) {
  37.     testStr = randomString(length)
  38.     time += timeIt(() => f(testStr))
  39.   }
  40.   return time
  41. }
  42.  
  43. function compare(count, length, f1, f2) {
  44.   console.log('f1: ', iterate(count, length, f1))
  45.   console.log('f2: ', iterate(count, length, f2))
  46. }
  47.  
  48. function testSame() {
  49.   const s = randomString(10)
  50.   console.log(s)
  51.   if (replace(s) !== replaceRegex(s)) {
  52.     console.error('Result differ!')
  53.   }
  54. }
  55.  
  56. testSame()
  57. compare(10000, 10000, replaceRegex, replace)
Tags: JavaScript
Advertisement
Add Comment
Please, Sign In to add comment