Skip to content

Instantly share code, notes, and snippets.

@imsickofmaps
Created May 27, 2013 17:34
Show Gist options
  • Save imsickofmaps/5658220 to your computer and use it in GitHub Desktop.
Save imsickofmaps/5658220 to your computer and use it in GitHub Desktop.
For cohort analysis on logins
function checkEmbedded(dates) {
// takes an array of ISO string formatted dates and determines
// they have signed in a minimum 1x per week over the past four weeks
var today = new Date();
var week = 7*24*60*60*1000;
dates.sort();
dates.reverse();
if (dates.length < 4){
// hasn't visited more than 4 times yet
return false;
} else {
// been 4 times so validate no less than 7 days between each visit
var forth = new Date(dates[3]); // Check 4th date not over 4 weeks
var last = new Date(dates[dates.length-1]); // Check last date no less than 4 weeks
if (((today-forth)/(week*4))>1 || (today-last) < (week*4)){
// the 4th date is older than 4 weeks old might as well stop now
return false;
} else {
var last_date = new Date(dates[0]); // skip the first
for (var i=1;i<dates.length;i++){
var this_date = new Date(dates[i]);
if (((today-this_date)/(week*4))<1){
// still under four weeks
if ((last_date-this_date)>week) {
// Gap is greater than 7 days
return false;
} else {
// Gap is less, get ready for next loop
last_date = this_date;
}
} else {
// we're now over four weeks without issues from today so stop
return true;
}
}
return true; // In case there's just four good weeks
}
}
}
function checkCohort(signup, dates) {
// Checks for the following scenarios and returns one of the four states:
// 1. Embedded (Sign in minimum 1x per week over the past 4 weeks)
// 2. Active (Sign in a minimum of 1x per month in the past 4 weeks)
// 3. Deactive (Have been part of the platform for more than 4 weeks and yet have not
// achieved Active or Embedded status)
// 4. Initial (have signed in but have not been part of the platform for a full month yet)
// signup should be timestamp of signup, dates an array of ISO string formatted dates
var today = new Date();
var week = 7*24*60*60*1000;
var sign_up = new Date(signup);
if (((today-sign_up)/(week*4))<1){
// less than four weeks since signup
return "initial";
} else {
// more than four weeks since signup
if (dates.length === 0){
return "deactive";
} else {
if (checkEmbedded(dates)) {
return "embedded";
} else {
// check if any of the dates are in the last month
dates.sort();
dates.reverse();
for (var i=1;i<dates.length;i++){
var this_date = new Date(dates[i]);
if (((today-this_date)/(week*4))<1){
return "active";
}
}
// drop back to deactive
return "deactive";
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment