AbTestingManager.coffee 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. define [
  2. "base"
  3. "libs/md5"
  4. ], (App) ->
  5. App.factory "abTestManager", ($http, ipCookie) ->
  6. _buildCookieKey = (testName, bucket)->
  7. key = "sl_abt_#{testName}_#{bucket}"
  8. console.log key
  9. return key
  10. _getTestCookie = (testName, bucket)->
  11. cookieKey = _buildCookieKey(testName, bucket)
  12. cookie = ipCookie(cookieKey)
  13. console.log cookieKey, cookie
  14. return cookie
  15. _persistCookieStep = (testName, bucket, newStep)->
  16. cookieKey = _buildCookieKey(testName, bucket)
  17. ipCookie(cookieKey, {step:newStep}, {expires:100, path:"/"})
  18. console.log("persisting", cookieKey, {step:newStep})
  19. ga('send', 'event', 'ab_tests', "#{testName}:#{bucket}", "step-#{newStep}")
  20. _checkIfStepIsNext = (cookieStep, newStep)->
  21. console.log cookieStep, newStep, "checking if step is next"
  22. if !cookieStep? and newStep != 0
  23. return false
  24. else if newStep == 0
  25. return true
  26. else if (cookieStep+1) == newStep
  27. return true
  28. else
  29. return false
  30. _getUsersHash = (testName)->
  31. sl_user_test_token = "sl_utt"
  32. user_uuid = ipCookie(sl_user_test_token)
  33. if !user_uuid?
  34. user_uuid = Math.random()
  35. ipCookie(sl_user_test_token, user_uuid, {expires:365, path:"/"})
  36. hash = CryptoJS.MD5("#{user_uuid}:#{testName}")
  37. return hash
  38. processTestWithStep: processTestWithStep = (testName, bucket, newStep)->
  39. currentCookieStep = _getTestCookie(testName, bucket)?.step
  40. if _checkIfStepIsNext(currentCookieStep, newStep)
  41. _persistCookieStep(testName, bucket, newStep)
  42. getABTestBucket: getABTestBucket = (test_name, buckets) ->
  43. hash = _getUsersHash(test_name)
  44. bucketIndex = parseInt(hash.toString().slice(0,2), 16) % (buckets?.length or 2)
  45. return buckets[bucketIndex]
  46. App.controller "AbTestController", ($scope, abTestManager)->
  47. testKeys = _.keys(window.ab)
  48. _.each window.ab, (event)->
  49. abTestManager.processTestWithStep event.testName, event.bucket, event.step