Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function timeIt(f) {
- const t0 = Date.now()
- const r = f()
- const t1 = Date.now()
- return t1-t0
- }
- function randomString(length) {
- let str = '';
- const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890. '
- for(i = 0; i < length; i++) {
- const c = Math.floor(Math.random() * chars.length)
- str += chars[c]
- }
- return str
- }
- function replaceRegex(str) {
- return str.replace(/[aeiou]/gi, '')
- }
- function replace(str) {
- const vowels = ['a','e','i','o','u','A','E','I','O','U']
- let newStr = '';
- for(i = 0; i < str.length; i++) {
- let c = str.charAt(i)
- if (vowels.indexOf(c) === -1) {
- newStr += c
- }
- }
- return newStr
- }
- function iterate(count, length, f) {
- let time = 0
- for(let i = 0; i < count; i++) {
- testStr = randomString(length)
- time += timeIt(() => f(testStr))
- }
- return time
- }
- function compare(count, length, f1, f2) {
- console.log('f1: ', iterate(count, length, f1))
- console.log('f2: ', iterate(count, length, f2))
- }
- function testSame() {
- const s = randomString(10)
- console.log(s)
- if (replace(s) !== replaceRegex(s)) {
- console.error('Result differ!')
- }
- }
- testSame()
- compare(10000, 10000, replaceRegex, replace)
Advertisement
Add Comment
Please, Sign In to add comment