AbTestingManager.coffee 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. define [
  2. "base"
  3. "libs/md5"
  4. ], (App) ->
  5. App.factory "abTestManager", ($http, ipCookie) ->
  6. _buildCookieKey = (testName)-> "sl_abt_#{testName}"
  7. _getTestCookie = (testName)->
  8. cookieKey = _buildCookieKey(testName)
  9. return ipCookie(cookieKey)
  10. _persistCookieStep = (testName, newStep)->
  11. ipCookie(_buildCookieKey(testName), step:newStep, {expires:10})
  12. ga('send', 'event', 'ab_tests', testName, {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. processTestWithStep: processTestWithStep = (testName, newStep)->
  23. currentCookieStep = _getTestCookie(testName)?.step
  24. if _checkIfStepIsNext(currentCookieStep, newStep)
  25. _persistCookieStep(testName, newStep)
  26. getABTestBucket: getABTestBucket = (user_id, test_name, buckets) ->
  27. hash = CryptoJS.MD5("#{user_id}:#{test_name}")
  28. bucketIndex = parseInt(hash.toString().slice(0,2), 16) % (buckets?.length or 2)
  29. return buckets[bucketIndex]
  30. App.controller "AbTestController", ($scope, abTestManager)->
  31. testKeys = _.keys(window.ab)
  32. _.each testKeys, (testName)->
  33. abTestManager.processTestWithStep testName, window.ab[testName]?.step