AbTestingManager.coffee 1.6 KB

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