Skip to content

Instantly share code, notes, and snippets.

@huikang
Forked from garbados/custom.js
Created January 21, 2018 03:38
Show Gist options
  • Save huikang/ea9194dbd29c3190d110a233775f38ab to your computer and use it in GitHub Desktop.
Save huikang/ea9194dbd29c3190d110a233775f38ab to your computer and use it in GitHub Desktop.
Sample CouchDB map functions for working with dates without a library.
function(doc){
// handle a custom format using methods in the date object
var format = "{getFullYear}/{getMonth}/{getDate}",
date = new Date(doc.created_at),
// use a regular expression to replace parts of our format string
formatted_date = format.replace(/\{(\w+)\}/g, function(str, func){
var time = date[func]();
// if `func` is `getMonth` we must offset by one
if(func === 'getMonth'){
time += 1;
}
return time;
});
emit(formatted_date, doc.created_at);
}
function(doc){
// use built-in methods for ISO formatting
var date = new Date(doc.created_at);
emit(date.getTime(), date.toISOString());
}
function(doc){
// given a format string as a regex...
var format = /^(\d{1,4})\/(\d{1,2})\/(\d{1,2})$/;
if(doc.key){
// we check if they match
var match = doc.key.match(format);
if(match){
// and use our knowledge of what each capture field should be
// to create a date object
var date = new Date(match[1], match[2], match[3]);
emit(doc.key, date.getTime());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment