Skip to content

Instantly share code, notes, and snippets.

@imsickofmaps
Created May 24, 2013 17:27
Show Gist options
  • Save imsickofmaps/5645102 to your computer and use it in GitHub Desktop.
Save imsickofmaps/5645102 to your computer and use it in GitHub Desktop.
Javascript function that takes an array of ISO string formatted dates related to a users signin activity and determines they have signed in a minimum 1x per week over the past four weeks. Used to determine if they are "Embedded" in cohort terms.
// bad
dates = ["2013-04-02T08:27:01.209Z", "2013-04-26T08:27:01.209Z", "2013-05-16T08:27:01.209Z", "2013-05-23T08:27:01.209Z", "2013-05-24T08:27:01.209Z"];
// good
dates = ["2013-04-25T08:27:01.209Z", "2013-04-31T08:27:01.209Z", "2013-05-06T08:27:01.209Z", "2013-05-13T08:27:01.209Z", "2013-05-20T08:27:01.209Z", "2013-05-24T08:27:01.209Z"];
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
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment