diff --git a/app/assets/javascripts/my_modules/results.js b/app/assets/javascripts/my_modules/results.js index 8853fc3ce..10473f399 100644 --- a/app/assets/javascripts/my_modules/results.js +++ b/app/assets/javascripts/my_modules/results.js @@ -12,6 +12,7 @@ function initHandsOnTables(root) { rowHeaders: true, colHeaders: true, fillHandle: false, + formulas: true, cells: function (row, col, prop) { var cellProperties = {}; @@ -181,29 +182,6 @@ function expandResult(result) { renderTable($(result).find("div.step-result-hot-table")); } - -initHandsOnTables($(document)); -initResultCommentTabAjax(); -expandAllResults(); -initTutorial(); -applyCollapseLinkCallBack(); - -initCommentOptions("ul.content-comments"); -initEditComments("#results"); -initDeleteComments("#results"); - -$(function () { - $("#results-collapse-btn").click(function () { - $('.result .panel-collapse').collapse('hide'); - $(document).find("span.collapse-result-icon").each(function() { - $(this).addClass("glyphicon-collapse-down"); - $(this).removeClass("glyphicon-collapse-up"); - }); - }); - - $("#results-expand-btn").click(expandAllResults); -}); - function renderTable(table) { $(table).handsontable("render"); // Yet another dirty hack to solve HandsOnTable problems @@ -358,6 +336,28 @@ function processResult(ev, resultTypeEnum, editMode, forS3) { // This checks if the ctarget param exist in the // rendered url and opens the comment tab $(document).ready(function(){ + initHandsOnTables($(document)); + initResultCommentTabAjax(); + expandAllResults(); + initTutorial(); + applyCollapseLinkCallBack(); + + initCommentOptions("ul.content-comments"); + initEditComments("#results"); + initDeleteComments("#results"); + + $(function () { + $("#results-collapse-btn").click(function () { + $('.result .panel-collapse').collapse('hide'); + $(document).find("span.collapse-result-icon").each(function() { + $(this).addClass("glyphicon-collapse-down"); + $(this).removeClass("glyphicon-collapse-up"); + }); + }); + + $("#results-expand-btn").click(expandAllResults); + }); + if( getParam('ctarget') ){ var target = "#"+ getParam('ctarget'); $(target).find('a.comment-tab-link').click(); diff --git a/app/assets/javascripts/protocols/steps.js b/app/assets/javascripts/protocols/steps.js index 2158edf50..878915e36 100644 --- a/app/assets/javascripts/protocols/steps.js +++ b/app/assets/javascripts/protocols/steps.js @@ -291,6 +291,7 @@ function initHandsOnTable(root) { rowHeaders: true, colHeaders: true, fillHandle: false, + formulas: true, cells: function (row, col, prop) { var cellProperties = {}; @@ -338,6 +339,7 @@ function initEditableHandsOnTable(root) { rowHeaders: true, colHeaders: true, contextMenu: true, + formulas: true, preventOverflow: 'horizontal' }); @@ -648,30 +650,6 @@ function expandStep(step) { }); } -// On init -initCallBacks(); -initHandsOnTable($(document)); -expandAllSteps(); -setupAssetsLoading(); - -// Init comments edit/delete -initCommentOptions("ul.content-comments"); -initEditComments("#steps"); -initDeleteComments("#steps"); - -$(function () { - - $("[data-action='collapse-steps']").click(function () { - $('.step .panel-collapse').collapse('hide'); - $(document).find("span.collapse-step-icon").each(function() { - $(this).addClass("glyphicon-collapse-down"); - $(this).removeClass("glyphicon-collapse-up"); - }); - }); - - $("[data-action='expand-steps']").click(expandAllSteps); -}); - function renderTable(table) { $(table).handsontable("render"); // Yet another dirty hack to solve HandsOnTable problems @@ -679,3 +657,29 @@ function renderTable(table) { $(table).find(".ht_master .wtHolder").css("height", "100%"); } } + +$(document).ready(function() { + // On init + initCallBacks(); + initHandsOnTable($(document)); + expandAllSteps(); + setupAssetsLoading(); + + // Init comments edit/delete + initCommentOptions("ul.content-comments"); + initEditComments("#steps"); + initDeleteComments("#steps"); + + $(function () { + + $("[data-action='collapse-steps']").click(function () { + $('.step .panel-collapse').collapse('hide'); + $(document).find("span.collapse-step-icon").each(function() { + $(this).addClass("glyphicon-collapse-down"); + $(this).removeClass("glyphicon-collapse-up"); + }); + }); + + $("[data-action='expand-steps']").click(expandAllSteps); + }); +}) diff --git a/app/assets/javascripts/reports/new.js b/app/assets/javascripts/reports/new.js index dc639501c..11eff9163 100644 --- a/app/assets/javascripts/reports/new.js +++ b/app/assets/javascripts/reports/new.js @@ -43,7 +43,8 @@ function initializeHandsonTable(el) { colHeaders: headers, columnSorting: true, editor: false, - copyPaste: false + copyPaste: false, + formulas: true }); el.handsontable("getInstance").loadData(data); el.handsontable("getInstance").sort(3, order); @@ -61,7 +62,8 @@ function initializeHandsonTable(el) { rowHeaders: true, colHeaders: true, editor: false, - copyPaste: false + copyPaste: false, + formulas: true }); el.handsontable("getInstance").loadData(data); } @@ -1191,17 +1193,29 @@ function showTutorial() { return tutorialProjectId == currentProjectId; } -/** - * ACTUAL CODE - */ -initializeReportElements($(REPORT_CONTENT)); +$(document).ready(function() { + /** + * ACTUAL CODE + */ + initializeReportElements($(REPORT_CONTENT)); + initializeGlobalReportSort(); + initializePrintPopup(); + initializeSaveToPdf(); + initializeSaveReport(); + initializeAddContentsModal(); + initializeSidebarNavigation(); + initializeUnsavedWorkDialog(); + initializeTutorial(); -initializeReportSidebartruncation(); -initializeGlobalReportSort(); -initializePrintPopup(); -initializeSaveToPdf(); -initializeSaveReport(); -initializeAddContentsModal(); -initializeSidebarNavigation(); -initializeUnsavedWorkDialog(); -initializeTutorial(); + $(".report-nav-link").each( function(){ + truncateLongString( $(this), 30); + }); +}) + +$(document).change(function(){ + setTimeout(function(){ + $(".report-nav-link").each( function(){ + truncateLongString( $(this), 30); + }); + }, 1000); +}); diff --git a/app/assets/javascripts/results/result_tables.js b/app/assets/javascripts/results/result_tables.js index 6c9e91ee8..eca1279d2 100644 --- a/app/assets/javascripts/results/result_tables.js +++ b/app/assets/javascripts/results/result_tables.js @@ -17,6 +17,7 @@ function initEditableHandsOnTable(root) { rowHeaders: true, colHeaders: true, contextMenu: true, + formulas: true, preventOverflow: 'horizontal' }); }); diff --git a/app/views/my_modules/results.html.erb b/app/views/my_modules/results.html.erb index c6087de90..f2193f5d1 100644 --- a/app/views/my_modules/results.html.erb +++ b/app/views/my_modules/results.html.erb @@ -54,3 +54,16 @@ <%= javascript_include_tag "results/result_texts" %> <%= javascript_include_tag "results/result_tables" %> <%= javascript_include_tag "results/result_assets" %> + + +<%= javascript_include_tag "lodash" %> +<%= javascript_include_tag "numeral" %> +<%= javascript_include_tag "numeric" %> +<%= javascript_include_tag "md5" %> +<%= javascript_include_tag "jstat" %> +<%= javascript_include_tag "formula" %> +<%= javascript_include_tag "parser" %> +<%= javascript_include_tag "ruleJS" %> +<%= javascript_include_tag "handsontable.formula" %> +<%= javascript_include_tag "big.min" %> +<%= stylesheet_link_tag "handsontable.formula" %> diff --git a/app/views/protocols/_steps.html.erb b/app/views/protocols/_steps.html.erb index f2d94300c..5869c5cfa 100644 --- a/app/views/protocols/_steps.html.erb +++ b/app/views/protocols/_steps.html.erb @@ -30,4 +30,17 @@ <% end %> -<%= javascript_include_tag "protocols/steps" %> \ No newline at end of file +<%= javascript_include_tag "protocols/steps" %> + + +<%= javascript_include_tag "lodash" %> +<%= javascript_include_tag "numeral" %> +<%= javascript_include_tag "numeric" %> +<%= javascript_include_tag "md5" %> +<%= javascript_include_tag "jstat" %> +<%= javascript_include_tag "formula" %> +<%= javascript_include_tag "parser" %> +<%= javascript_include_tag "ruleJS" %> +<%= javascript_include_tag "handsontable.formula" %> +<%= javascript_include_tag "big.min" %> +<%= stylesheet_link_tag "handsontable.formula" %> diff --git a/app/views/reports/new.html.erb b/app/views/reports/new.html.erb index c09fd89ec..2635a4be8 100644 --- a/app/views/reports/new.html.erb +++ b/app/views/reports/new.html.erb @@ -75,3 +75,16 @@ <%= javascript_include_tag "handsontable.full.min" %> <%= javascript_include_tag("reports/new") %> + + +<%= javascript_include_tag "lodash" %> +<%= javascript_include_tag "numeral" %> +<%= javascript_include_tag "numeric" %> +<%= javascript_include_tag "md5" %> +<%= javascript_include_tag "jstat" %> +<%= javascript_include_tag "formula" %> +<%= javascript_include_tag "parser" %> +<%= javascript_include_tag "ruleJS" %> +<%= javascript_include_tag "handsontable.formula" %> +<%= javascript_include_tag "big.min" %> +<%= stylesheet_link_tag "handsontable.formula" %> diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb index d2e4fef14..f50042763 100644 --- a/config/initializers/assets.rb +++ b/config/initializers/assets.rb @@ -7,55 +7,68 @@ Rails.application.config.assets.version = '1.0' # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. -# application.js, application.css, and all non-JS/CSS in app/assets folder are already added. -Rails.application.config.assets.precompile += %w( underscore.js ) -Rails.application.config.assets.precompile += %w( jsPlumb-2.0.4-min.js ) -Rails.application.config.assets.precompile += %w( jsnetworkx.js ) -Rails.application.config.assets.precompile += %w( handsontable.full.min.js ) -Rails.application.config.assets.precompile += %w( users/settings/preferences.js ) -Rails.application.config.assets.precompile += %w( users/settings/organizations.js ) -Rails.application.config.assets.precompile += %w( users/settings/organizations/add_user_modal.js ) -Rails.application.config.assets.precompile += %w( users/settings/organization.js ) -Rails.application.config.assets.precompile += %w( my_modules/activities.js ) -Rails.application.config.assets.precompile += %w( my_modules/protocols.js ) -Rails.application.config.assets.precompile += %w( my_modules/protocols/protocol_status_bar.js ) -Rails.application.config.assets.precompile += %w( my_modules/results.js ) -Rails.application.config.assets.precompile += %w( results/result_tables.js ) -Rails.application.config.assets.precompile += %w( results/result_assets.js ) -Rails.application.config.assets.precompile += %w( results/result_texts.js ) -Rails.application.config.assets.precompile += %w( users/registrations/edit.js ) -Rails.application.config.assets.precompile += %w( jquery-ui/draggable.js ) -Rails.application.config.assets.precompile += %w( jquery-ui/droppable.js ) -Rails.application.config.assets.precompile += %w( jquery.ui.touch-punch.min.js ) -Rails.application.config.assets.precompile += %w( bootstrap-colorselector.js ) -Rails.application.config.assets.precompile += %w( eventPause-min.js ) -Rails.application.config.assets.precompile += %w( sidebar.js ) -Rails.application.config.assets.precompile += %w( samples/samples.js ) -Rails.application.config.assets.precompile += %w( samples/sample_datatable.js ) -Rails.application.config.assets.precompile += %w( projects/index.js ) -Rails.application.config.assets.precompile += %w( samples/samples_importer.js ) -Rails.application.config.assets.precompile += %w( projects/canvas.js ) -Rails.application.config.assets.precompile += %w( experiments/dropdown_actions.js ) -Rails.application.config.assets.precompile += %w( reports/index.js ) -Rails.application.config.assets.precompile += %w( reports/new.js ) -Rails.application.config.assets.precompile += %w( protocols/index.js ) -Rails.application.config.assets.precompile += %w( protocols/header.js ) -Rails.application.config.assets.precompile += %w( protocols/steps.js ) -Rails.application.config.assets.precompile += %w( protocols/edit.js ) -Rails.application.config.assets.precompile += %w( protocols/import_export/eln_table.js ) -Rails.application.config.assets.precompile += %w( protocols/import_export/import.js ) -Rails.application.config.assets.precompile += %w( protocols/import_export/export.js ) -Rails.application.config.assets.precompile += %w( datatables.js ) -Rails.application.config.assets.precompile += %w( search/index.js ) -Rails.application.config.assets.precompile += %w( navigation.js ) -Rails.application.config.assets.precompile += %w( datatables.css ) -Rails.application.config.assets.precompile += %w( my_modules.js ) -Rails.application.config.assets.precompile += %w( direct-upload.js ) -Rails.application.config.assets.precompile += %w( canvas-to-blob.min.js ) -Rails.application.config.assets.precompile += %w( Sortable.min.js ) -Rails.application.config.assets.precompile += %w( reports_pdf.css ) -Rails.application.config.assets.precompile += %w( jszip.min.js ) -Rails.application.config.assets.precompile += %w( assets.js ) -Rails.application.config.assets.precompile += %w( comments.js ) -Rails.application.config.assets.precompile += %w( projects/show.js ) -Rails.application.config.assets.precompile += %w( projects/introdutory_popup.js ) +# application.js application.css, and all non-JS/CSS in app/assets folder are already added. +Rails.application.config.assets.precompile += %w(underscore.js) +Rails.application.config.assets.precompile += %w(jsPlumb-2.0.4-min.js) +Rails.application.config.assets.precompile += %w(jsnetworkx.js) +Rails.application.config.assets.precompile += %w(handsontable.full.min.js) +Rails.application.config.assets.precompile += %w(users/settings/preferences.js) +Rails.application.config.assets.precompile += %w(users/settings/organizations.js) +Rails.application.config.assets.precompile += %w(users/settings/organizations/add_user_modal.js) +Rails.application.config.assets.precompile += %w(users/settings/organization.js) +Rails.application.config.assets.precompile += %w(my_modules/activities.js) +Rails.application.config.assets.precompile += %w(my_modules/protocols.js) +Rails.application.config.assets.precompile += %w(my_modules/protocols/protocol_status_bar.js) +Rails.application.config.assets.precompile += %w(my_modules/results.js) +Rails.application.config.assets.precompile += %w(results/result_tables.js) +Rails.application.config.assets.precompile += %w(results/result_assets.js) +Rails.application.config.assets.precompile += %w(results/result_texts.js) +Rails.application.config.assets.precompile += %w(users/registrations/edit.js) +Rails.application.config.assets.precompile += %w(jquery-ui/draggable.js) +Rails.application.config.assets.precompile += %w(jquery-ui/droppable.js) +Rails.application.config.assets.precompile += %w(jquery.ui.touch-punch.min.js) +Rails.application.config.assets.precompile += %w(bootstrap-colorselector.js) +Rails.application.config.assets.precompile += %w(eventPause-min.js) +Rails.application.config.assets.precompile += %w(sidebar.js) +Rails.application.config.assets.precompile += %w(samples/samples.js) +Rails.application.config.assets.precompile += %w(samples/sample_datatable.js) +Rails.application.config.assets.precompile += %w(projects/index.js) +Rails.application.config.assets.precompile += %w(samples/samples_importer.js) +Rails.application.config.assets.precompile += %w(projects/canvas.js) +Rails.application.config.assets.precompile += %w(experiments/dropdown_actions.js) +Rails.application.config.assets.precompile += %w(reports/index.js) +Rails.application.config.assets.precompile += %w(reports/new.js) +Rails.application.config.assets.precompile += %w(protocols/index.js) +Rails.application.config.assets.precompile += %w(protocols/header.js) +Rails.application.config.assets.precompile += %w(protocols/steps.js) +Rails.application.config.assets.precompile += %w(protocols/edit.js) +Rails.application.config.assets.precompile += %w(protocols/import_export/eln_table.js) +Rails.application.config.assets.precompile += %w(protocols/import_export/import.js) +Rails.application.config.assets.precompile += %w(protocols/import_export/export.js) +Rails.application.config.assets.precompile += %w(datatables.js) +Rails.application.config.assets.precompile += %w(search/index.js) +Rails.application.config.assets.precompile += %w(navigation.js) +Rails.application.config.assets.precompile += %w(datatables.css) +Rails.application.config.assets.precompile += %w(my_modules.js) +Rails.application.config.assets.precompile += %w(direct-upload.js) +Rails.application.config.assets.precompile += %w(canvas-to-blob.min.js) +Rails.application.config.assets.precompile += %w(Sortable.min.js) +Rails.application.config.assets.precompile += %w(reports_pdf.css) +Rails.application.config.assets.precompile += %w(jszip.min.js) +Rails.application.config.assets.precompile += %w(assets.js) +Rails.application.config.assets.precompile += %w(comments.js) +Rails.application.config.assets.precompile += %w(projects/show.js) +Rails.application.config.assets.precompile += %w(projects/introdutory_popup.js) + +# Libraries needed for Handsontable formulas +Rails.application.config.assets.precompile += %w(lodash.js) +Rails.application.config.assets.precompile += %w(numeral.js) +Rails.application.config.assets.precompile += %w(numeric.js) +Rails.application.config.assets.precompile += %w(md5.js) +Rails.application.config.assets.precompile += %w(jstat.js) +Rails.application.config.assets.precompile += %w(formula.js) +Rails.application.config.assets.precompile += %w(parser.js) +Rails.application.config.assets.precompile += %w(ruleJS.js) +Rails.application.config.assets.precompile += %w(handsontable.formula.js) +Rails.application.config.assets.precompile += %w(handsontable.formula.css) +Rails.application.config.assets.precompile += %w(big.min.js) diff --git a/vendor/assets/javascripts/big.min.js b/vendor/assets/javascripts/big.min.js new file mode 100644 index 000000000..83e9e8dd7 --- /dev/null +++ b/vendor/assets/javascripts/big.min.js @@ -0,0 +1 @@ +/* big.js v3.1.3 https://github.com/MikeMcl/big.js/LICENCE */(function(global){"use strict";var DP=20,RM=1,MAX_DP=1e6,MAX_POWER=1e6,E_NEG=-7,E_POS=21,P={},isValid=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Big;function bigFactory(){function Big(n){var x=this;if(!(x instanceof Big)){return n===void 0?bigFactory():new Big(n)}if(n instanceof Big){x.s=n.s;x.e=n.e;x.c=n.c.slice()}else{parse(x,n)}x.constructor=Big}Big.prototype=P;Big.DP=DP;Big.RM=RM;Big.E_NEG=E_NEG;Big.E_POS=E_POS;return Big}function format(x,dp,toE){var Big=x.constructor,i=dp-(x=new Big(x)).e,c=x.c;if(c.length>++dp){rnd(x,i,Big.RM)}if(!c[0]){++i}else if(toE){i=dp}else{c=x.c;i=x.e+i+1}for(;c.length1?c[0]+"."+c.join("").slice(1):c[0])+(i<0?"e":"e+")+i:x.toString()}function parse(x,n){var e,i,nL;if(n===0&&1/n<0){n="-0"}else if(!isValid.test(n+="")){throwErr(NaN)}x.s=n.charAt(0)=="-"?(n=n.slice(1),-1):1;if((e=n.indexOf("."))>-1){n=n.replace(".","")}if((i=n.search(/e/i))>0){if(e<0){e=i}e+=+n.slice(i+1);n=n.substring(0,i)}else if(e<0){e=n.length}for(i=0;n.charAt(i)=="0";i++){}if(i==(nL=n.length)){x.c=[x.e=0]}else{for(;n.charAt(--nL)=="0";){}x.e=e-i-1;x.c=[];for(e=0;i<=nL;x.c[e++]=+n.charAt(i++)){}}return x}function rnd(x,dp,rm,more){var u,xc=x.c,i=x.e+dp+1;if(rm===1){more=xc[i]>=5}else if(rm===2){more=xc[i]>5||xc[i]==5&&(more||i<0||xc[i+1]!==u||xc[i-1]&1)}else if(rm===3){more=more||xc[i]!==u||i<0}else{more=false;if(rm!==0){throwErr("!Big.RM!")}}if(i<1||!xc[0]){if(more){x.e=-dp;x.c=[1]}else{x.c=[x.e=0]}}else{xc.length=i--;if(more){for(;++xc[i]>9;){xc[i]=0;if(!i--){++x.e;xc.unshift(1)}}}for(i=xc.length;!xc[--i];xc.pop()){}}return x}function throwErr(message){var err=new Error(message);err.name="BigError";throw err}P.abs=function(){var x=new this.constructor(this);x.s=1;return x};P.cmp=function(y){var xNeg,x=this,xc=x.c,yc=(y=new x.constructor(y)).c,i=x.s,j=y.s,k=x.e,l=y.e;if(!xc[0]||!yc[0]){return!xc[0]?!yc[0]?0:-j:i}if(i!=j){return i}xNeg=i<0;if(k!=l){return k>l^xNeg?1:-1}i=-1;j=(k=xc.length)<(l=yc.length)?k:l;for(;++iyc[i]^xNeg?1:-1}}return k==l?0:k>l^xNeg?1:-1};P.div=function(y){var x=this,Big=x.constructor,dvd=x.c,dvs=(y=new Big(y)).c,s=x.s==y.s?1:-1,dp=Big.DP;if(dp!==~~dp||dp<0||dp>MAX_DP){throwErr("!Big.DP!")}if(!dvd[0]||!dvs[0]){if(dvd[0]==dvs[0]){throwErr(NaN)}if(!dvs[0]){throwErr(s/0)}return new Big(s*0)}var dvsL,dvsT,next,cmp,remI,u,dvsZ=dvs.slice(),dvdI=dvsL=dvs.length,dvdL=dvd.length,rem=dvd.slice(0,dvsL),remL=rem.length,q=y,qc=q.c=[],qi=0,digits=dp+(q.e=x.e-y.e)+1;q.s=s;s=digits<0?0:digits;dvsZ.unshift(0);for(;remL++remL?1:-1}else{for(remI=-1,cmp=0;++remIrem[remI]?1:-1;break}}}if(cmp<0){for(dvsT=remL==dvsL?dvs:dvsZ;remL;){if(rem[--remL]digits){rnd(q,dp,Big.RM,rem[0]!==u)}return q};P.eq=function(y){return!this.cmp(y)};P.gt=function(y){return this.cmp(y)>0};P.gte=function(y){return this.cmp(y)>-1};P.lt=function(y){return this.cmp(y)<0};P.lte=function(y){return this.cmp(y)<1};P.sub=P.minus=function(y){var i,j,t,xLTy,x=this,Big=x.constructor,a=x.s,b=(y=new Big(y)).s;if(a!=b){y.s=-b;return x.plus(y)}var xc=x.c.slice(),xe=x.e,yc=y.c,ye=y.e;if(!xc[0]||!yc[0]){return yc[0]?(y.s=-b,y):new Big(xc[0]?x:0)}if(a=xe-ye){if(xLTy=a<0){a=-a;t=xc}else{ye=xe;t=yc}t.reverse();for(b=a;b--;t.push(0)){}t.reverse()}else{j=((xLTy=xc.length0){for(;b--;xc[i++]=0){}}for(b=i;j>a;){if(xc[--j]0){ye=xe;t=yc}else{a=-a;t=xc}t.reverse();for(;a--;t.push(0)){}t.reverse()}if(xc.length-yc.length<0){t=yc;yc=xc;xc=t}a=yc.length;for(b=0;a;){b=(xc[--a]=xc[a]+yc[a]+b)/10|0;xc[a]%=10}if(b){xc.unshift(b);++ye}for(a=xc.length;xc[--a]===0;xc.pop()){}y.c=xc;y.e=ye;return y};P.pow=function(n){var x=this,one=new x.constructor(1),y=one,isNeg=n<0;if(n!==~~n||n<-MAX_POWER||n>MAX_POWER){throwErr("!pow!")}n=isNeg?-n:n;for(;;){if(n&1){y=y.times(x)}n>>=1;if(!n){break}x=x.times(x)}return isNeg?one.div(y):y};P.round=function(dp,rm){var x=this,Big=x.constructor;if(dp==null){dp=0}else if(dp!==~~dp||dp<0||dp>MAX_DP){throwErr("!round!")}rnd(x=new Big(x),dp,rm==null?Big.RM:rm);return x};P.sqrt=function(){var estimate,r,approx,x=this,Big=x.constructor,xc=x.c,i=x.s,e=x.e,half=new Big("0.5");if(!xc[0]){return new Big(x)}if(i<0){throwErr(NaN)}i=Math.sqrt(x.toString());if(i===0||i===1/0){estimate=xc.join("");if(!(estimate.length+e&1)){estimate+="0"}r=new Big(Math.sqrt(estimate).toString());r.e=((e+1)/2|0)-(e<0||e&1)}else{r=new Big(i.toString())}i=r.e+(Big.DP+=4);do{approx=r;r=half.times(approx.plus(x.div(approx)))}while(approx.c.slice(0,i).join("")!==r.c.slice(0,i).join(""));rnd(r,Big.DP-=4,Big.RM);return r};P.mul=P.times=function(y){var c,x=this,Big=x.constructor,xc=x.c,yc=(y=new Big(y)).c,a=xc.length,b=yc.length,i=x.e,j=y.e;y.s=x.s==y.s?1:-1;if(!xc[0]||!yc[0]){return new Big(y.s*0)}y.e=i+j;if(ai;){b=c[j]+yc[i]*xc[j-i-1]+b;c[j--]=b%10;b=b/10|0}c[j]=(c[j]+b)%10}if(b){++y.e}if(!c[0]){c.shift()}for(i=c.length;!c[--i];c.pop()){}y.c=c;return y};P.toString=P.valueOf=P.toJSON=function(){var x=this,Big=x.constructor,e=x.e,str=x.c.join(""),strL=str.length;if(e<=Big.E_NEG||e>=Big.E_POS){str=str.charAt(0)+(strL>1?"."+str.slice(1):"")+(e<0?"e":"e+")+e}else if(e<0){for(;++e;str="0"+str){}str="0."+str}else if(e>0){if(++e>strL){for(e-=strL;e--;str+="0"){}}else if(e1){str=str.charAt(0)+"."+str.slice(1)}return x.s<0&&x.c[0]?"-"+str:str};P.toExponential=function(dp){if(dp==null){dp=this.c.length-1}else if(dp!==~~dp||dp<0||dp>MAX_DP){throwErr("!toExp!")}return format(this,dp,1)};P.toFixed=function(dp){var str,x=this,Big=x.constructor,neg=Big.E_NEG,pos=Big.E_POS;Big.E_NEG=-(Big.E_POS=1/0);if(dp==null){str=x.toString()}else if(dp===~~dp&&dp>=0&&dp<=MAX_DP){str=format(x,x.e+dp);if(x.s<0&&x.c[0]&&str.indexOf("-")<0){str="-"+str}}Big.E_NEG=neg;Big.E_POS=pos;if(!str){throwErr("!toFix!")}return str};P.toPrecision=function(sd){if(sd==null){return this.toString()}else if(sd!==~~sd||sd<1||sd>MAX_DP){throwErr("!toPre!")}return format(this,sd-1,2)};Big=bigFactory();if(typeof define==="function"&&define.amd){define(function(){return Big})}else if(typeof module!=="undefined"&&module.exports){module.exports=Big}else{global.Big=Big}})(this); diff --git a/vendor/assets/javascripts/formula.js b/vendor/assets/javascripts/formula.js new file mode 100644 index 000000000..75f6aa481 --- /dev/null +++ b/vendor/assets/javascripts/formula.js @@ -0,0 +1,5830 @@ +// Copyright (c) 2012 Sutoiku, Inc. + +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Some algorithms have been ported from Apache OpenOffice: + +/************************************************************** + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + *************************************************************/ +/*jslint evil: true*/ +/*global define */ + +(function () { + var root = this; + + var Formula = root.Formula = {}; + var _ = root._; + var numeric = root.numeric; + var numeral = root.numeral; + var jStat = root.jStat; + var moment = root.moment; + var lodash = _; + var md5 = root.md5; + var _s = _.str; + + if (typeof exports !== "undefined") { + module.exports = exportModule( + require('numeric'), + require('numeral'), + require('jStat'), + require('moment'), + require('lodash'), + require('underscore.string'), + require('blueimp-md5') + ); + } else if (typeof define === "function" && define.amd) { + define( + 'formula', + ['numeric', 'numeral', 'jstat', 'moment', 'lodash', 'underscore.string', 'md5'], + exportModule + ); + } else { + Formula = exportModule(numeric, numeral, jStat, moment, lodash, _s, md5); + return Formula; + } + + function exportModule(numeric, numeral, jStat, moment, _, _s, md5) { + var MEMOIZED_FACT = []; + + var SQRT2PI = 2.5066282746310002; + + var WEEK_STARTS = [ + undefined, + 0, + 1, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 1, + 2, + 3, + 4, + 5, + 6, + 0 + ]; + + var WEEK_TYPES = [ + [], + [1, 2, 3, 4, 5, 6, 7], + [7, 1, 2, 3, 4, 5, 6], + [6, 0, 1, 2, 3, 4, 5], + [], + [], + [], + [], + [], + [], + [], + [7, 1, 2, 3, 4, 5, 6], + [6, 7, 1, 2, 3, 4, 5], + [5, 6, 7, 1, 2, 3, 4], + [4, 5, 6, 7, 1, 2, 3], + [3, 4, 5, 6, 7, 1, 2], + [2, 3, 4, 5, 6, 7, 1], + [1, 2, 3, 4, 5, 6, 7] + ]; + + var WEEKEND_TYPES = [ + [], + [6, 0], + [0, 1], + [1, 2], + [2, 3], + [3, 4], + [4, 5], + [5, 6], + undefined, + undefined, + undefined, + [0], + [1], + [2], + [3], + [4], + [5], + [6] + ]; + + var simplifyArguments = function (arguments) { + for (var prop in arguments) { + if (_.isArray(arguments[prop])) { + arguments[prop] = Formula.FLATTEN(arguments[prop]); + } + } + return arguments; + }; + + // Override some functions + Formula.UNIQUE = function () { + return _.unique(arguments); + }; + + Formula.FLATTEN = function () { + return _.flatten(arguments); + }; + + // Generate a callback function + Formula.FUNCTION = function () { + var args = Array.prototype.slice.call(arguments); + var expression = args[args.length - 1]; + var regexp = /(\w+)\(/g; + var newExpression = expression.replace(regexp, function () { + return "Formulae." + arguments[0]; + }); + + args[args.length - 1] = "return " + newExpression + ";"; + if (newExpression !== expression) { + args.unshift('Formulae'); + } + + return Function.apply(null, args); + }; + + // Moment functions + Formula.MOMENT = function (timestamp, format) { + return moment(timestamp).format(format); + }; + + Formula.MOMENTADD = function (start_date, period, number) { + return moment(start_date).add(period, number); + }; + + Formula.MOMENTDIFF = function (start_date, end_date, period) { + return moment(end_date).diff(moment.utc(start_date), period); + }; + + Formula.MOMENTSUB = function (start_date, period, number) { + return moment(start_date).subtract(period, number); + }; + + Formula.MOMENTUTC = function (timestamp, format) { + return moment.utc(timestamp).format(format); + }; + + Formula.MOMENTUTCADD = function (start_date, period, number) { + return moment.utc(start_date).add(period, number); + }; + + Formula.MOMENTUTCDIFF = function (start_date, end_date, period) { + return moment.utc(end_date).diff(moment.utc(start_date), period); + }; + + Formula.MOMENTUTCSUB = function (start_date, period, number) { + return moment.utc(start_date).subtract(period, number); + }; + + Formula.MOMENTUNIX = function (unixTime) { + return moment.unix(unixTime).toDate(); + }; + + Formula.MOMENTFORMAT = function (date, format) { + return moment(date).format(format); + }; + + Formula.MOMENTISLEAPYEAR = function (date, format) { + return moment(date, format).isLeapYear(); + }; + + Formula.MOMENTISDST = function (date, format) { + return moment(date, format).isDST(); + }; + + Formula.MOMENTSTARTOF = function (date, units, format) { + return moment(date, format).startOf(units).toDate(); + }; + + Formula.MOMENTENDOF = function (date, units, format) { + return moment(date, format).endOf(units).toDate(); + }; + + Formula.MOMENTISAFTER = function (date1, date2, format) { + return moment(date1, format).isAfter(moment(date2, format)); + }; + + Formula.MOMENTISBEFORE = function (date1, date2, format) { + return moment(date1, format).isBefore(moment(date2, format)); + }; + + Formula.INTERVAL = function (second) { + var year = Math.floor(second/946080000); + second = second%946080000; + var month = Math.floor(second/2592000); + second = second%2592000; + var day = Math.floor(second/86400); + second = second%86400; + + var hour = Math.floor(second/3600); + second = second%3600; + var min = Math.floor(second/60); + second = second%60; + var sec = second; + + year = (year > 0) ? year + 'Y' : ''; + month = (month > 0) ? month + 'M' : ''; + day = (day > 0) ? day + 'D' : ''; + hour = (hour > 0) ? hour + 'H' : ''; + min = (min > 0) ? min + 'M' : ''; + sec = (sec > 0) ? sec + 'S' : ''; + + return 'P' + year + month + day + + 'T' + hour + min + sec; + }; + + // Custom Functions + Formula.ARGSCONCAT = function (args) { + var result = []; + for (var i = 0; i < args.length; i++) { + result = result.concat(args[i]); + } + return result; + }; + + Formula.ARGSTOARRAY = function (args) { + return Array.prototype.slice.call(args, 0); + }; + + Formula.CLEANFLOAT = function (number) { + var power = Math.pow(10, 14); + return Math.round(number * power) / power; + }; + + Formula.COUNTIN = function (range, value) { + var result = 0; + for (var i = 0; i < range.length; i++) { + if (range[i] === value) { + result++; + } + } + return result; + }; + + Formula.FINDFIELD = function(database, title) { + var index = null; + for (var i = 0; i < database.length; i++) { + if (database[i][0] === title) { + index = i; + break; + } + } + + // Return error if the input field title is incorrect + if (index == null) { + return '#VALUE!'; + } + return index; + }; + + Formula.FINDRESULTINDEX = function(database, criteria) { + var maxCriteriaLength = criteria[0].length; + for (var i = 1; i < criteria.length; i++) { + if (criteria[i].length > maxCriteriaLength) { + maxCriteriaLength = criteria[i].length; + } + } + var columnResultIndexes = []; + for (i = 1; i < maxCriteriaLength; i++) { + var rowResultIndexes = []; + for (var j = 0; j < criteria.length; j++) { + if (criteria[j].length < maxCriteriaLength) { + continue; + } + var criteriaTitle = criteria[j][0]; + var criteriaIndex = Formula.FINDFIELD(database, criteriaTitle); + var criteriaValues = _.rest(database[criteriaIndex]); + var count = 0; + var singleResultIndexes = []; + for (var k = 0; k < criteriaValues.length; k++) { + if (eval(criteriaValues[k] + criteria[j][i])) { + singleResultIndexes[count++] = k; + } + } + rowResultIndexes[j] = singleResultIndexes; + } + columnResultIndexes[i - 1] = _.intersection.apply(_, rowResultIndexes); + } + + var resultIndexes = _.union.apply(_, columnResultIndexes); + return resultIndexes; + }; + + // Database functions + Formula.DAVERAGE = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var sum = 0; + for (var i = 0; i < resultIndexes.length; i++) { + sum += targetFields[resultIndexes[i]]; + } + var average = Formula.IF(resultIndexes.length === 0, "#DIV/0!", sum / resultIndexes.length); + return average; + }; + + Formula.DCOUNT = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var targetValues = []; + for (var i = 0; i < resultIndexes.length; i++) { + targetValues[i] = targetFields[resultIndexes[i]]; + } + return Formula.COUNT(targetValues); + }; + + Formula.DCOUNTA = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var targetValues = []; + for (var i = 0; i < resultIndexes.length; i++) { + targetValues[i] = targetFields[resultIndexes[i]]; + } + return Formula.COUNTA(targetValues); + }; + + Formula.DGET = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + // Return error if no record meets the criteria + if (resultIndexes.length === 0) { + return '#VALUE!'; + } + // Returns the #NUM! error value because more than one record meets the + // criteria + if (resultIndexes.length > 1) { + return '#NUM!'; + } + + return targetFields[resultIndexes[0]]; + }; + + Formula.DMAX = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var maxValue = targetFields[resultIndexes[0]]; + for (var i = 1; i < resultIndexes.length; i++) { + if (maxValue < targetFields[resultIndexes[i]]) { + maxValue = targetFields[resultIndexes[i]]; + } + } + return maxValue; + }; + + Formula.DMIN = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var minValue = targetFields[resultIndexes[0]]; + for (var i = 1; i < resultIndexes.length; i++) { + if (minValue > targetFields[resultIndexes[i]]) { + minValue = targetFields[resultIndexes[i]]; + } + } + return minValue; + }; + + Formula.DPRODUCT = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var targetValues = []; + for (var i = 0; i < resultIndexes.length; i++) { + targetValues[i] = targetFields[resultIndexes[i]]; + } + targetValues = _.compact(targetValues); + var result = 1; + for (i = 0; i < targetValues.length; i++) { + result *= targetValues[i]; + } + return result; + }; + + Formula.DSTDEV = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var targetValues = []; + for (var i = 0; i < resultIndexes.length; i++) { + targetValues[i] = targetFields[resultIndexes[i]]; + } + targetValues = _.compact(targetValues); + return Formula.STDEVS(targetValues); + }; + + Formula.DSTDEVP = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var targetValues = []; + for (var i = 0; i < resultIndexes.length; i++) { + targetValues[i] = targetFields[resultIndexes[i]]; + } + targetValues = _.compact(targetValues); + return Formula.STDEVP(targetValues); + }; + + Formula.DSUM = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var targetValues = []; + for (var i = 0; i < resultIndexes.length; i++) { + targetValues[i] = targetFields[resultIndexes[i]]; + } + return Formula.SUM(targetValues); + }; + + Formula.DVAR = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var targetValues = []; + for (var i = 0; i < resultIndexes.length; i++) { + targetValues[i] = targetFields[resultIndexes[i]]; + } + return Formula.VARS(targetValues); + }; + + Formula.DVARP = function(database, field, criteria) { + // Return error if field is not a number and not a string + if (isNaN(field) && (typeof field !== "string")) { + return '#VALUE!'; + } + var resultIndexes = Formula.FINDRESULTINDEX(database, criteria); + var targetFields = []; + if (typeof field === "string") { + var index = Formula.FINDFIELD(database, field); + targetFields = _.rest(database[index]); + } else { + targetFields = _.rest(database[field]); + } + var targetValues = []; + for (var i = 0; i < resultIndexes.length; i++) { + targetValues[i] = targetFields[resultIndexes[i]]; + } + return Formula.VARP(targetValues); + }; + + Formula.GETJSON = function (file) { + var request = new XMLHttpRequest(); + request.open('GET', file, false); + request.send(null); + if (request.status === 200) { + return JSON.parse(request.responseText); + } + }; + + + // Date functions + Formula.DATE = function () { + if (!arguments.length) { + return new Date(); + } + + if (arguments.length === 1) { + return new Date(arguments[0]); + } + + var args = arguments; + args[1] = args[1] - 1; // Monthes are between 0 and 11. + return new (Date.bind.apply(Date, [Date].concat([].splice.call(args, 0))))(); + }; + + Formula.DATEVALUE = function (date_text) { + return Math.ceil((moment(date_text) - moment('1900-1-1')) / 86400000) + 2; + }; + + Formula.DAY = function (date) { + return new Date(date).getDate(); + }; + + Formula.DAYS = function (end_date, start_date) { + return moment(new Date(end_date)).diff(moment(new Date(start_date)), 'days'); + }; + + Formula.DAYS360 = function (start_date, end_date, method) { + var start = moment(new Date(start_date)); + var end = moment(new Date(end_date)); + var smd = 31; + var emd = 31; + var sd = start.date(); + var ed = end.date(); + if (method) { + sd = (sd === 31) ? 30 : sd; + ed = (ed === 31) ? 30 : ed; + } + else { + if (start.month() === 1) { + smd = start.daysInMonth(); + } + if (end.month() === 1) { + emd = end.daysInMonth(); + } + sd = (sd === smd) ? 30 : sd; + if (sd === 30 || sd === smd) { + ed = (ed === emd) ? 30 : ed; + } + } + return 360 * (end.year() - start.year()) + 30 * (end.month() - start.month()) + (ed - sd); + }; + + Formula.EDATE = function (start_date, months) { + return moment(new Date(start_date)).add('months', months).toDate(); + }; + + Formula.EOMONTH = function (start_date, months) { + var edate = moment(new Date(start_date)).add('months', months); + return new Date(edate.year(), edate.month(), edate.daysInMonth()); + }; + + Formula.FROMNOW = function (timestamp, nosuffix) { + return moment(new Date(timestamp)).fromNow(nosuffix); + }; + + Formula.HOUR = function (timestamp) { + return (timestamp <= 1) ? Math.floor(24 * timestamp) : new Date(timestamp).getHours(); + }; + + Formula.MINUTE = function (timestamp) { + return (timestamp <= 1) ? Math.floor(24 * 60 * timestamp) - 60 * Math.floor(24 * timestamp) : new Date(timestamp).getMinutes(); + }; + + Formula.ISOWEEKNUM = function (date) { + return moment(new Date(date)).format('w'); + }; + + Formula.MONTH = function (timestamp) { + return new Date(timestamp).getMonth() + 1; + }; + + Formula.NETWORKDAYS = function (start_date, end_date, holidays) { + return Formula.NETWORKDAYSINTL(start_date, end_date, 1, holidays); + }; + + Formula.NETWORKDAYSINTL = function (start_date, end_date, weekend, holidays) { + var weekend_type = (typeof weekend === 'undefined') ? 1 : weekend; + var weekend_days = WEEKEND_TYPES[weekend_type]; + var sd = moment(start_date); + var ed = moment(end_date); + var net_days = ed.diff(sd, 'days') + 1; + var net_work_days = net_days; + var cd = sd; + var holiday_dates = []; + if (typeof holidays !== 'undefined') { + for (var i = 0; i < holidays.length; i++) { + holiday_dates[i] = moment(new Date(holidays[i])).format('MM-DD-YYYY'); + } + } + + if (!weekend_days.length && !holiday_dates.length) { + // No need to loop here. + return net_work_days; + } + var j = 0; + while (j < net_days) { + if (weekend_days.indexOf(parseInt(cd.format('d'), 10)) >= 0) { + net_work_days--; + } else if (holiday_dates.indexOf(cd.format('MM-DD-YYYY')) >= 0) { + net_work_days--; + } + cd = cd.add('days', 1); + j++; + } + return net_work_days; + }; + + Formula.NOW = function () { + return new Date(); + }; + + Formula.SECOND = function (timestamp) { + return new Date(timestamp).getSeconds(); + }; + + Formula.TIME = function (hour, minute, second) { + return (3600 * hour + 60 * minute + second) / 86400; + }; + + Formula.TIMEVALUE = function (time_text) { + var timestamp = new Date(time_text); + return (3600 * timestamp.getHours() + 60 * timestamp.getMinutes() + timestamp.getSeconds()) / 86400; + }; + + Formula.TODAY = Formula.NOW; + + Formula.WEEKDAY = function (date, type) { + var week_day = moment(new Date(date)).format('d'); + var week_type = (typeof type === 'undefined') ? 1 : type; + return WEEK_TYPES[week_type][week_day]; + }; + + Formula.WEEKNUM = function (date, type) { + var current_date = moment(new Date(date)); + var january_first = moment(new Date(current_date.year(), 0, 1)); + var week_type = (typeof type === 'undefined') ? 1 : type; + var week_start = WEEK_STARTS[week_type]; + var first_day = january_first.format('d'); + var offset = (first_day < week_start) ? week_start - first_day + 1 : first_day - week_start; + if (week_type === 21) { + return Formula.ISOWEEKNUM(date); + } else { + return Math.floor(current_date.diff(january_first.subtract('days', offset), 'days') / 7) + 1; + } + }; + + Formula.WORKDAY = function (start_date, days, holidays) { + return Formula.WORKDAYINTL(start_date, days, 1, holidays); + }; + + Formula.WORKDAYINTL = function (start_date, days, weekend, holidays) { + var weekend_type = (typeof weekend === 'undefined') ? 1 : weekend; + var weekend_days = WEEKEND_TYPES[weekend_type]; + var sd = moment(new Date(start_date)); + var cd = sd; + var day_of_week = ''; + var holiday_dates = []; + if (typeof holidays !== 'undefined') { + for (var i = 0; i < holidays.length; i++) { + holiday_dates[i] = moment(new Date(holidays[i])).format('MM-DD-YYYY'); + } + } + var j = 0; + while (j < days) { + cd = cd.add('days', 1); + day_of_week = cd.format('d'); + if (weekend_days.indexOf(parseInt(day_of_week, 10)) < 0 && holiday_dates.indexOf(cd.format('MM-DD-YYYY')) < 0) { + j++; + } + } + return cd.toDate(); + }; + + Formula.YEAR = function (date) { + return new Date(date).getFullYear(); + }; + + Formula.YEARFRAC = function (start_date, end_date, basis) { + // Credits: David A. Wheeler [http://www.dwheeler.com/] + + // Initialize parameters + basis = (typeof basis === 'undefined') ? 0 : basis; + var sdate = moment(new Date(start_date)); + var edate = moment(new Date(end_date)); + + // Return error if either date is invalid + if (!sdate.isValid() || !edate.isValid()) { + return '#VALUE!'; + } + + // Return error if basis is neither 0, 1, 2, 3, or 4 + if ([0, 1, 2, 3, 4].indexOf(basis) === -1) { + return '#NUM!'; + } + + // Return zero if start_date and end_date are the same + if (sdate === edate) { + return 0; + } + + // Swap dates if start_date is later than end_date + if (sdate.diff(edate) > 0) { + edate = moment(new Date(start_date)); + sdate = moment(new Date(end_date)); + } + + // Lookup years, months, and days + var syear = sdate.year(); + var smonth = sdate.month(); + var sday = sdate.date(); + var eyear = edate.year(); + var emonth = edate.month(); + var eday = edate.date(); + + switch (basis) { + case 0: + // US (NASD) 30/360 + // Note: if eday == 31, it stays 31 if sday < 30 + if (sday === 31 && eday === 31) { + sday = 30; + eday = 30; + } else if (sday === 31) { + sday = 30; + } else if (sday === 30 && eday === 31) { + eday = 30; + } else if (smonth === 1 && emonth === 1 && sdate.daysInMonth() === sday && edate.daysInMonth() === eday) { + sday = 30; + eday = 30; + } else if (smonth === 1 && sdate.daysInMonth() === sday) { + sday = 30; + } + return ((eday + emonth * 30 + eyear * 360) - (sday + smonth * 30 + syear * 360)) / 360; + + case 1: + // Actual/actual + var feb29Between = function (date1, date2) { + // Requires year2 == (year1 + 1) or year2 == year1 + // Returns TRUE if February 29 is between the two dates (date1 may be February 29), with two possibilities: + // year1 is a leap year and date1 <= Februay 29 of year1 + // year2 is a leap year and date2 > Februay 29 of year2 + + var mar1year1 = moment(new Date(date1.year(), 2, 1)); + if (moment([date1.year()]).isLeapYear() && date1.diff(mar1year1) < 0 && date2.diff(mar1year1) >= 0) { + return true; + } + var mar1year2 = moment(new Date(date2.year(), 2, 1)); + if (moment([date2.year()]).isLeapYear() && date2.diff(mar1year2) >= 0 && date1.diff(mar1year2) < 0) { + return true; + } + return false; + }; + var ylength = 365; + if (syear === eyear || ((syear + 1) === eyear) && ((smonth > emonth) || ((smonth === emonth) && (sday >= eday)))) { + if (syear === eyear && moment([syear]).isLeapYear()) { + ylength = 366; + } else if (feb29Between(sdate, edate) || (emonth === 1 && eday === 29)) { + ylength = 366; + } + return edate.diff(sdate, 'days') / ylength; + } else { + var years = (eyear - syear) + 1; + var days = moment(new Date(eyear + 1, 0, 1)).diff(moment(new Date(syear, 0, 1)), 'days'); + var average = days / years; + return edate.diff(sdate, 'days') / average; + } + break; + + case 2: + // Actual/360 + return edate.diff(sdate, 'days') / 360; + + case 3: + // Actual/365 + return edate.diff(sdate, 'days') / 365; + + case 4: + // European 30/360 + if (sday === 31) { + sday = 30; + } + + if (eday === 31) { + eday = 30; + } + // Remarkably, do NOT change February 28 or February 29 at ALL + return ((eday + emonth * 30 + eyear * 360) - (sday + smonth * 30 + syear * 360)) / 360; + } + }; + + // Engineering functions + + // This function is extracted from the source code of SheetJS/bessel: + // https://github.com/SheetJS/bessel/blob/master/bessel.js#L144 + Formula.BESSELI = (function() { + function horner(arr, v) { + return arr.reduce(function(z, w) { + return v*z + w; + }, 0); + } + var b0_a = [1.0, 3.5156229, 3.0899424, 1.2067492, 0.2659732, 0.360768e-1, 0.45813e-2].reverse(); + var b0_b = [0.39894228, 0.1328592e-1, 0.225319e-2, -0.157565e-2, 0.916281e-2, -0.2057706e-1, 0.2635537e-1, -0.1647633e-1, 0.392377e-2].reverse(); + function bessel0(x) { + if(x <= 3.75) { + return horner(b0_a, x*x/(3.75*3.75)); + } + return Math.exp(Math.abs(x))/Math.sqrt(Math.abs(x))*horner(b0_b, 3.75/Math.abs(x)); + } + + var b1_a = [0.5, 0.87890594, 0.51498869, 0.15084934, 0.2658733e-1, 0.301532e-2, 0.32411e-3].reverse(); + var b1_b = [0.39894228, -0.3988024e-1, -0.362018e-2, 0.163801e-2, -0.1031555e-1, 0.2282967e-1, -0.2895312e-1, 0.1787654e-1, -0.420059e-2].reverse(); + function bessel1(x) { + if(x < 3.75) { + return x * horner(b1_a, x*x/(3.75*3.75)); + } + return (x < 0 ? -1 : 1) * Math.exp(Math.abs(x))/Math.sqrt(Math.abs(x))*horner(b1_b, 3.75/Math.abs(x)); + } + + return function besseli(x, n) { + n = Math.round(n); + if(n === 0) { + return bessel0(x); + } + if(n === 1) { + return bessel1(x); + } + if(n < 0) { + throw 'BESSELI Order (' + n + ') must be nonnegative'; + } + if(Math.abs(x) === 0) { + return 0; + } + + var ret, j, tox = 2 / Math.abs(x), m, bip, bi, bim; + m=2*Math.round((n+Math.round(Math.sqrt(40*n)))/2); + bip=ret=0.0; + bi=1.0; + for (j=m;j>0;j--) { + bim=j*tox*bi + bip; + bip=bi; bi=bim; + if (Math.abs(bi) > 1E10) { + bi *= 1E-10; + bip *= 1E-10; + ret *= 1E-10; + } + if(j === n) { + ret = bip; + } + } + ret *= besseli(x, 0) / bi; + return x < 0 && (n%2) ? -ret : ret; + }; + + })(); + + // This function is extracted from the source code of SheetJS/bessel: + // https://github.com/SheetJS/bessel/blob/master/bessel.js#L25 + Formula.BESSELJ = (function() { + function horner(arr, v) { + return arr.reduce(function(z, w) { + return v*z + w; + }, 0); + } + var b0_a1a = [57568490574.0,-13362590354.0,651619640.7,-11214424.18,77392.33017,-184.9052456].reverse(); + var b0_a2a = [57568490411.0,1029532985.0,9494680.718,59272.64853,267.8532712,1.0].reverse(); + var b0_a1b = [1.0, -0.1098628627e-2, 0.2734510407e-4, -0.2073370639e-5, 0.2093887211e-6].reverse(); + var b0_a2b = [-0.1562499995e-1, 0.1430488765e-3, -0.6911147651e-5, 0.7621095161e-6, -0.934935152e-7].reverse(); + var W = 0.636619772; // 2 / Math.PI + + function bessel0(x) { + var a, a1, a2, y = x * x, xx = Math.abs(x) - 0.785398164; + if(Math.abs(x) < 8) { + a1 = horner(b0_a1a, y); + a2 = horner(b0_a2a, y); + a = a1/a2; + } + else { + y = 64 / y; + a1 = horner(b0_a1b, y); + a2 = horner(b0_a2b, y); + a = Math.sqrt(W/Math.abs(x))*(Math.cos(xx)*a1-Math.sin(xx)*a2*8/Math.abs(x)); + } + return a; + } + var b1_a1a = [72362614232.0,-7895059235.0,242396853.1,-2972611.439, 15704.48260, -30.16036606].reverse(); + var b1_a2a = [144725228442.0, 2300535178.0, 18583304.74, 99447.43394, 376.9991397, 1.0].reverse(); + var b1_a1b = [1.0, 0.183105e-2, -0.3516396496e-4, 0.2457520174e-5, -0.240337019e-6].reverse(); + var b1_a2b = [0.04687499995, -0.2002690873e-3, 0.8449199096e-5, -0.88228987e-6, 0.105787412e-6].reverse(); + function bessel1(x) { + var a, a1, a2, y = x*x, xx = Math.abs(x) - 2.356194491; + if(Math.abs(x)< 8) { + a1 = x*horner(b1_a1a, y); + a2 = horner(b1_a2a, y); + a = a1 / a2; + } else { + y = 64 / y; + a1=horner(b1_a1b, y); + a2=horner(b1_a2b, y); + a=Math.sqrt(W/Math.abs(x))*(Math.cos(xx)*a1-Math.sin(xx)*a2*8/Math.abs(x)); + if(x < 0) { + a = -a; + } + } + return a; + } + + function _bessel_iter(x, n, f0, f1, sign) { + if(!sign) { + sign = -1; + } + var tdx = 2 / x, f2; + if(n === 0) { + return f0; + } + if(n === 1) { + return f1; + } + for(var o = 1; o !== n; ++o) { + f2 = f1 * o * tdx + sign * f0; + f0 = f1; f1 = f2; + } + return f1; + } + + return function besselj(x, n) { + n = Math.round(n); + if(n === 0) { + return bessel0(Math.abs(x)); + } + if(n === 1) { + return bessel1(Math.abs(x)); + } + if(n < 0) { + throw 'BESSELJ: Order (' + n + ') must be nonnegative'; + } + if(Math.abs(x) === 0) { + return 0; + } + + var ret, j, tox = 2 / Math.abs(x), m, jsum, sum, bjp, bj, bjm; + if(Math.abs(x) > n) { + ret = _bessel_iter(x, n, bessel0(Math.abs(x)), bessel1(Math.abs(x)),-1); + } else { + m=2*Math.floor((n+Math.floor(Math.sqrt(40*n)))/2); + jsum=0; + bjp=ret=sum=0.0; + bj=1.0; + for (j=m;j>0;j--) { + bjm=j*tox*bj-bjp; + bjp=bj; + bj=bjm; + if (Math.abs(bj) > 1E10) { + bj *= 1E-10; + bjp *= 1E-10; + ret *= 1E-10; + sum *= 1E-10; + } + if (jsum) { + sum += bj; + } + jsum=!jsum; + if (j === n) { + ret=bjp; + } + } + sum=2.0*sum-bj; + ret /= sum; + } + return x < 0 && (n%2) ? -ret : ret; + }; + })(); + + // This function is extracted from the source code of SheetJS/bessel: + // https://github.com/SheetJS/bessel/blob/master/bessel.js#L186 + Formula.BESSELK = (function() { + function horner(arr, v) { + return arr.reduce(function(z, w) { + return v*z + w; + }, 0); + } + var b0_a = [-0.57721566, 0.42278420, 0.23069756, 0.3488590e-1, 0.262698e-2, 0.10750e-3, 0.74e-5].reverse(); + var b0_b = [1.25331414, -0.7832358e-1, 0.2189568e-1, -0.1062446e-1, 0.587872e-2, -0.251540e-2, 0.53208e-3].reverse(); + function bessel0(x) { + if(x <= 2) { + return -Math.log(x/2)*Formula.BESSELI(x,0) + horner(b0_a,x*x/4); + } + return Math.exp(-x)/Math.sqrt(x)*horner(b0_b,2/x); + } + + var b1_a = [1.0, 0.15443144, -0.67278579, -0.18156897, -0.1919402e-1, -0.110404e-2, -0.4686e-4].reverse(); + var b1_b = [1.25331414, 0.23498619, -0.3655620e-1, 0.1504268e-1, -0.780353e-2, 0.325614e-2, -0.68245e-3].reverse(); + function bessel1(x) { + if(x <= 2) { + return Math.log(x/2)*Formula.BESSELI(x,1) + (1/x)*horner(b1_a,x*x/4); + } + return Math.exp(-x)/Math.sqrt(x)*horner(b1_b,2/x); + } + + function _bessel_iter(x, n, f0, f1, sign) { + if(!sign) { + sign = -1; + } + var tdx = 2 / x, f2; + if(n === 0) { + return f0; + } + if(n === 1) { + return f1; + } + for(var o = 1; o !== n; ++o) { + f2 = f1 * o * tdx + sign * f0; + f0 = f1; f1 = f2; + } + return f1; + } + + function _bessel_wrap(bessel0, bessel1, name, nonzero, sign) { + return function bessel(x,n) { + if(n === 0) { + return bessel0(x); + } + if(n === 1) { + return bessel1(x); + } + if(n < 0) { + throw name + ': Order (' + n + ') must be nonnegative'; + } + if(nonzero === 1 && x === 0) { + throw name + ': Undefined when x == 0'; + } + if(nonzero === 2 && x <= 0) { + throw name + ': Undefined when x <= 0'; + } + var b0 = bessel0(x), b1 = bessel1(x); + return _bessel_iter(x, n, b0, b1, sign); + }; + } + + return _bessel_wrap(bessel0, bessel1, 'BESSELK', 2, 1); + })(); + + // This function is extracted from the source code of SheetJS/bessel: + // https://github.com/SheetJS/bessel/blob/master/bessel.js#L101 + Formula.BESSELY = (function() { + function horner(arr, v) { + return arr.reduce(function(z, w) { + return v*z + w; + }, 0); + } + var b0_a1a = [-2957821389.0, 7062834065.0, -512359803.6, 10879881.29, -86327.92757, 228.4622733].reverse(); + var b0_a2a = [40076544269.0, 745249964.8, 7189466.438, 47447.26470, 226.1030244, 1.0].reverse(); + var b0_a1b = [1.0, -0.1098628627e-2, 0.2734510407e-4, -0.2073370639e-5, 0.2093887211e-6].reverse(); + var b0_a2b = [-0.1562499995e-1, 0.1430488765e-3, -0.6911147651e-5, 0.7621095161e-6, -0.934945152e-7].reverse(); + + var W = 0.636619772; + function bessel0(x) { + var a, a1, a2, y = x * x, xx = x - 0.785398164; + if(x < 8) { + a1 = horner(b0_a1a, y); + a2 = horner(b0_a2a, y); + a = a1/a2 + W * Formula.BESSELJ(x,0) * Math.log(x); + } else { + y = 64 / y; + a1 = horner(b0_a1b, y); + a2 = horner(b0_a2b, y); + a = Math.sqrt(W/x)*(Math.sin(xx)*a1+Math.cos(xx)*a2*8/x); + } + return a; + } + + var b1_a1a = [-0.4900604943e13, 0.1275274390e13, -0.5153438139e11, 0.7349264551e9, -0.4237922726e7, 0.8511937935e4].reverse(); + var b1_a2a = [0.2499580570e14, 0.4244419664e12, 0.3733650367e10, 0.2245904002e8, 0.1020426050e6, 0.3549632885e3, 1].reverse(); + var b1_a1b = [1.0, 0.183105e-2, -0.3516396496e-4, 0.2457520174e-5, -0.240337019e-6].reverse(); + var b1_a2b = [0.04687499995, -0.2002690873e-3, 0.8449199096e-5, -0.88228987e-6, 0.105787412e-6].reverse(); + function bessel1(x) { + var a, a1, a2, y = x*x, xx = x - 2.356194491; + if(x < 8) { + a1 = x*horner(b1_a1a, y); + a2 = horner(b1_a2a, y); + a = a1/a2 + W * (Formula.BESSELJ(x,1) * Math.log(x) - 1 / x); + } else { + y = 64 / y; + a1=horner(b1_a1b, y); + a2=horner(b1_a2b, y); + a=Math.sqrt(W/x)*(Math.sin(xx)*a1+Math.cos(xx)*a2*8/x); + } + return a; + } + + function _bessel_iter(x, n, f0, f1, sign) { + if(!sign) { + sign = -1; + } + var tdx = 2 / x, f2; + if(n === 0) { + return f0; + } + if(n === 1) { + return f1; + } + for(var o = 1; o !== n; ++o) { + f2 = f1 * o * tdx + sign * f0; + f0 = f1; f1 = f2; + } + return f1; + } + + function _bessel_wrap(bessel0, bessel1, name, nonzero, sign) { + return function bessel(x,n) { + if(n === 0) { + return bessel0(x); + } + if(n === 1) { + return bessel1(x); + } + if(n < 0) { + throw name + ': Order (' + n + ') must be nonnegative'; + } + if(nonzero === 1 && x === 0) { + throw name + ': Undefined when x == 0'; + } + if(nonzero === 2 && x <= 0) { + throw name + ': Undefined when x <= 0'; + } + var b0 = bessel0(x), b1 = bessel1(x); + return _bessel_iter(x, n, b0, b1, sign); + }; + } + + return _bessel_wrap(bessel0, bessel1, 'BESSELY', 1, -1); + })(); + + Formula.VALIDBIN = function (number) { + return (/^[01]{1,10}$/).test(number); + }; + + Formula.BIN2DEC = function (number) { + // Return error if number is not binary or contains more than 10 characters (10 digits) + if (!Formula.VALIDBIN(number)) { + return '#NUM!'; + } + + // Convert binary number to decimal + var result = parseInt(number, 2); + + // Handle negative numbers + var stringified = number.toString(); + if (stringified.length === 10 && stringified.substring(0, 1) === '1') { + return parseInt(stringified.substring(1), 2) - 512; + } else { + return result; + } + }; + + Formula.BIN2HEX = function (number, places) { + // Return error if number is not binary or contains more than 10 characters (10 digits) + if (!Formula.VALIDBIN(number)) { + return '#NUM!'; + } + + // Ignore places and return a 10-character hexadecimal number if number is negative + var stringified = number.toString(); + if (stringified.length === 10 && stringified.substring(0, 1) === '1') { + return (1099511627264 + parseInt(stringified.substring(1), 2)).toString(16); + } + + // Convert binary number to hexadecimal + var result = parseInt(number, 2).toString(16); + + // Return hexadecimal number using the minimum number of characters necessary if places is undefined + if (typeof places === 'undefined') { + return result; + } else { + // Return error if places is nonnumeric + if (isNaN(places)) { + return '#VALUE!'; + } + + // Return error if places is negative + if (places < 0) { + return '#NUM!'; + } + + // Truncate places in case it is not an integer + places = Math.floor(places); + + // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) + return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; + } + }; + + Formula.BIN2OCT = function (number, places) { + // Return error if number is not binary or contains more than 10 characters (10 digits) + if (!Formula.VALIDBIN(number)) { + return '#NUM!'; + } + + // Ignore places and return a 10-character octal number if number is negative + var stringified = number.toString(); + if (stringified.length === 10 && stringified.substring(0, 1) === '1') { + return (1073741312 + parseInt(stringified.substring(1), 2)).toString(8); + } + + // Convert binary number to octal + var result = parseInt(number, 2).toString(8); + + // Return octal number using the minimum number of characters necessary if places is undefined + if (typeof places === 'undefined') { + return result; + } else { + // Return error if places is nonnumeric + if (isNaN(places)) { + return '#VALUE!'; + } + + // Return error if places is negative + if (places < 0) { + return '#NUM!'; + } + + // Truncate places in case it is not an integer + places = Math.floor(places); + + // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) + return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; + } + }; + + Formula.BITAND = function (number1, number2) { + // Return error if either number is a non-numeric value + if (isNaN(number1) || isNaN(number2)) { + return '#VALUE!'; + } + + // Return error if either number is less than 0 + if (number1 < 0 || number2 < 0) { + return '#NUM!'; + } + + // Return error if either number is a non-integer + if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { + return '#NUM!'; + } + + // Return error if either number is greater than (2^48)-1 + if (number1 > 281474976710655 || number2 > 281474976710655) { + return '#NUM!'; + } + + // Return bitwise AND of two numbers + return number1 & number2; + }; + + Formula.BITLSHIFT = function (number, shift) { + // Return error if either number is a non-numeric value + if (isNaN(number) || isNaN(shift)) { + return '#VALUE!'; + } + + // Return error if number is less than 0 + if (number < 0) { + return '#NUM!'; + } + + // Return error if number is a non-integer + if (Math.floor(number) !== number) { + return '#NUM!'; + } + + // Return error if number is greater than (2^48)-1 + if (number > 281474976710655) { + return '#NUM!'; + } + + // Return error if the absolute value of shift is greater than 53 + if (Math.abs(shift) > 53) { + return '#NUM!'; + } + + // Return number shifted by shift bits to the left or to the right if shift is negative + return (shift >= 0 ) ? number << shift : number >> -shift; + }; + + Formula.BITOR = function (number1, number2) { + // Return error if either number is a non-numeric value + if (isNaN(number1) || isNaN(number2)) { + return '#VALUE!'; + } + + // Return error if either number is less than 0 + if (number1 < 0 || number2 < 0) { + return '#NUM!'; + } + + // Return error if either number is a non-integer + if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { + return '#NUM!'; + } + + // Return error if either number is greater than (2^48)-1 + if (number1 > 281474976710655 || number2 > 281474976710655) { + return '#NUM!'; + } + + // Return bitwise OR of two numbers + return number1 | number2; + }; + + Formula.BITRSHIFT = function (number, shift) { + // Return error if either number is a non-numeric value + if (isNaN(number) || isNaN(shift)) { + return '#VALUE!'; + } + + // Return error if number is less than 0 + if (number < 0) { + return '#NUM!'; + } + + // Return error if number is a non-integer + if (Math.floor(number) !== number) { + return '#NUM!'; + } + + // Return error if number is greater than (2^48)-1 + if (number > 281474976710655) { + return '#NUM!'; + } + + // Return error if the absolute value of shift is greater than 53 + if (Math.abs(shift) > 53) { + return '#NUM!'; + } + + // Return number shifted by shift bits to the right or to the left if shift is negative + return (shift >= 0 ) ? number >> shift : number << -shift; + }; + + Formula.BITXOR = function (number1, number2) { + // Return error if either number is a non-numeric value + if (isNaN(number1) || isNaN(number2)) { + return '#VALUE!'; + } + + // Return error if either number is less than 0 + if (number1 < 0 || number2 < 0) { + return '#NUM!'; + } + + // Return error if either number is a non-integer + if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { + return '#NUM!'; + } + + // Return error if either number is greater than (2^48)-1 + if (number1 > 281474976710655 || number2 > 281474976710655) { + return '#NUM!'; + } + + // Return bitwise XOR of two numbers + return number1 ^ number2; + }; + + Formula.COMPLEX = function (real, imaginary, suffix) { + // Return error if either number is a non-numeric value + if (isNaN(real) || isNaN(imaginary)) { + return '#VALUE!'; + } + + // Set suffix + suffix = (typeof suffix === 'undefined') ? 'i' : suffix; + + // Return error if suffix is neither "i" nor "j" + if (suffix !== 'i' && suffix !== 'j') { + return '#VALUE!'; + } + + // Return complex number + if (real === 0 && imaginary === 0) { + return 0; + } else if (real === 0) { + return (imaginary === 1) ? suffix : imaginary.toString() + suffix; + } else if (imaginary === 0) { + return real.toString(); + } else { + var sign = (imaginary > 0) ? '+' : ''; + return real.toString() + sign + ((imaginary === 1) ? suffix : imaginary.toString() + suffix); + } + }; + + Formula.CONVERT = function (number, from_unit, to_unit) { + // Return error if number is a non-numeric value + if (isNaN(number)) { + return '#VALUE!'; + } + + // List of units supported by CONVERT and units defined by the International System of Units + // [Name, Symbol, Alternate symbols, Quantity, ISU, CONVERT, Conversion ratio] + var units = [ + ["a.u. of action", "?", null, "action", false, false, 1.05457168181818e-34], + ["a.u. of charge", "e", null, "electric_charge", false, false, 1.60217653141414e-19], + ["a.u. of energy", "Eh", null, "energy", false, false, 4.35974417757576e-18], + ["a.u. of length", "a?", null, "length", false, false, 5.29177210818182e-11], + ["a.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31], + ["a.u. of time", "?/Eh", null, "time", false, false, 2.41888432650516e-17], + ["admiralty knot", "admkn", null, "speed", false, true, 0.514773333], + ["ampere", "A", null, "electric_current", true, false, 1], + ["ampere per meter", "A/m", null, "magnetic_field_intensity", true, false, 1], + ["ångström", "Å", ["ang"], "length", false, true, 1e-10], + ["are", "ar", null, "area", false, true, 100], + ["astronomical unit", "ua", null, "length", false, false, 1.49597870691667e-11], + ["bar", "bar", null, "pressure", false, false, 100000], + ["barn", "b", null, "area", false, false, 1e-28], + ["becquerel", "Bq", null, "radioactivity", true, false, 1], + ["bit", "bit", ["b"], "information", false, true, 1], + ["btu", "BTU", ["btu"], "energy", false, true, 1055.05585262], + ["byte", "byte", null, "information", false, true, 8], + ["candela", "cd", null, "luminous_intensity", true, false, 1], + ["candela per square metre", "cd/m?", null, "luminance", true, false, 1], + ["coulomb", "C", null, "electric_charge", true, false, 1], + ["cubic ångström", "ang3", ["ang^3"], "volume", false, true, 1e-30], + ["cubic foot", "ft3", ["ft^3"], "volume", false, true, 0.028316846592], + ["cubic inch", "in3", ["in^3"], "volume", false, true, 0.000016387064], + ["cubic light-year", "ly3", ["ly^3"], "volume", false, true, 8.46786664623715e-47], + ["cubic metre", "m?", null, "volume", true, true, 1], + ["cubic mile", "mi3", ["mi^3"], "volume", false, true, 4168181825.44058], + ["cubic nautical mile", "Nmi3", ["Nmi^3"], "volume", false, true, 6352182208], + ["cubic Pica", "Pica3", ["Picapt3", "Pica^3", "Picapt^3"], "volume", false, true, 7.58660370370369e-8], + ["cubic yard", "yd3", ["yd^3"], "volume", false, true, 0.764554857984], + ["cup", "cup", null, "volume", false, true, 0.0002365882365], + ["dalton", "Da", ["u"], "mass", false, false, 1.66053886282828e-27], + ["day", "d", ["day"], "time", false, true, 86400], + ["degree", "°", null, "angle", false, false, 0.0174532925199433], + ["degrees Rankine", "Rank", null, "temperature", false, true, 0.555555555555556], + ["dyne", "dyn", ["dy"], "force", false, true, 0.00001], + ["electronvolt", "eV", ["ev"], "energy", false, true, 1.60217656514141], + ["ell", "ell", null, "length", false, true, 1.143], + ["erg", "erg", ["e"], "energy", false, true, 1e-7], + ["farad", "F", null, "electric_capacitance", true, false, 1], + ["fluid ounce", "oz", null, "volume", false, true, 0.0000295735295625], + ["foot", "ft", null, "length", false, true, 0.3048], + ["foot-pound", "flb", null, "energy", false, true, 1.3558179483314], + ["gal", "Gal", null, "acceleration", false, false, 0.01], + ["gallon", "gal", null, "volume", false, true, 0.003785411784], + ["gauss", "G", ["ga"], "magnetic_flux_density", false, true, 1], + ["grain", "grain", null, "mass", false, true, 0.0000647989], + ["gram", "g", null, "mass", false, true, 0.001], + ["gray", "Gy", null, "absorbed_dose", true, false, 1], + ["gross registered ton", "GRT", ["regton"], "volume", false, true, 2.8316846592], + ["hectare", "ha", null, "area", false, true, 10000], + ["henry", "H", null, "inductance", true, false, 1], + ["hertz", "Hz", null, "frequency", true, false, 1], + ["horsepower", "HP", ["h"], "power", false, true, 745.69987158227], + ["horsepower-hour", "HPh", ["hh", "hph"], "energy", false, true, 2684519.538], + ["hour", "h", ["hr"], "time", false, true, 3600], + ["imperial gallon (U.K.)", "uk_gal", null, "volume", false, true, 0.00454609], + ["imperial hundredweight", "lcwt", ["uk_cwt", "hweight"], "mass", false, true, 50.802345], + ["imperial quart (U.K)", "uk_qt", null, "volume", false, true, 0.0011365225], + ["imperial ton", "brton", ["uk_ton", "LTON"], "mass", false, true, 1016.046909], + ["inch", "in", null, "length", false, true, 0.0254], + ["international acre", "uk_acre", null, "area", false, true, 4046.8564224], + ["IT calorie", "cal", null, "energy", false, true, 4.1868], + ["joule", "J", null, "energy", true, true, 1], + ["katal", "kat", null, "catalytic_activity", true, false, 1], + ["kelvin", "K", ["kel"], "temperature", true, true, 1], + ["kilogram", "kg", null, "mass", true, true, 1], + ["knot", "kn", null, "speed", false, true, 0.514444444444444], + ["light-year", "ly", null, "length", false, true, 9460730472580800], + ["litre", "L", ["l", "lt"], "volume", false, true, 0.001], + ["lumen", "lm", null, "luminous_flux", true, false, 1], + ["lux", "lx", null, "illuminance", true, false, 1], + ["maxwell", "Mx", null, "magnetic_flux", false, false, 1e-18], + ["measurement ton", "MTON", null, "volume", false, true, 1.13267386368], + ["meter per hour", "m/h", ["m/hr"], "speed", false, true, 0.00027777777777778], + ["meter per second", "m/s", ["m/sec"], "speed", true, true, 1], + ["meter per second squared", "m?s??", null, "acceleration", true, false, 1], + ["parsec", "pc", ["parsec"], "length", false, true, 30856775814671900], + ["meter squared per second", "m?/s", null, "kinematic_viscosity", true, false, 1], + ["metre", "m", null, "length", true, true, 1], + ["miles per hour", "mph", null, "speed", false, true, 0.44704], + ["millimetre of mercury", "mmHg", null, "pressure", false, false, 133.322], + ["minute", "?", null, "angle", false, false, 0.000290888208665722], + ["minute", "min", ["mn"], "time", false, true, 60], + ["modern teaspoon", "tspm", null, "volume", false, true, 0.000005], + ["mole", "mol", null, "amount_of_substance", true, false, 1], + ["morgen", "Morgen", null, "area", false, true, 2500], + ["n.u. of action", "?", null, "action", false, false, 1.05457168181818e-34], + ["n.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31], + ["n.u. of speed", "c?", null, "speed", false, false, 299792458], + ["n.u. of time", "?/(me?c??)", null, "time", false, false, 1.28808866778687e-21], + ["nautical mile", "M", ["Nmi"], "length", false, true, 1852], + ["newton", "N", null, "force", true, true, 1], + ["œrsted", "Oe ", null, "magnetic_field_intensity", false, false, 79.5774715459477], + ["ohm", "Ω", null, "electric_resistance", true, false, 1], + ["ounce mass", "ozm", null, "mass", false, true, 0.028349523125], + ["pascal", "Pa", null, "pressure", true, false, 1], + ["pascal second", "Pa?s", null, "dynamic_viscosity", true, false, 1], + ["pferdestärke", "PS", null, "power", false, true, 735.49875], + ["phot", "ph", null, "illuminance", false, false, 0.0001], + ["pica (1/6 inch)", "pica", null, "length", false, true, 0.00035277777777778], + ["pica (1/72 inch)", "Pica", ["Picapt"], "length", false, true, 0.00423333333333333], + ["poise", "P", null, "dynamic_viscosity", false, false, 0.1], + ["pond", "pond", null, "force", false, true, 0.00980665], + ["pound force", "lbf", null, "force", false, true, 4.4482216152605], + ["pound mass", "lbm", null, "mass", false, true, 0.45359237], + ["quart", "qt", null, "volume", false, true, 0.000946352946], + ["radian", "rad", null, "angle", true, false, 1], + ["second", "?", null, "angle", false, false, 0.00000484813681109536], + ["second", "s", ["sec"], "time", true, true, 1], + ["short hundredweight", "cwt", ["shweight"], "mass", false, true, 45.359237], + ["siemens", "S", null, "electrical_conductance", true, false, 1], + ["sievert", "Sv", null, "equivalent_dose", true, false, 1], + ["slug", "sg", null, "mass", false, true, 14.59390294], + ["square ångström", "ang2", ["ang^2"], "area", false, true, 1e-20], + ["square foot", "ft2", ["ft^2"], "area", false, true, 0.09290304], + ["square inch", "in2", ["in^2"], "area", false, true, 0.00064516], + ["square light-year", "ly2", ["ly^2"], "area", false, true, 8.95054210748189e+31], + ["square meter", "m?", null, "area", true, true, 1], + ["square mile", "mi2", ["mi^2"], "area", false, true, 2589988.110336], + ["square nautical mile", "Nmi2", ["Nmi^2"], "area", false, true, 3429904], + ["square Pica", "Pica2", ["Picapt2", "Pica^2", "Picapt^2"], "area", false, true, 0.00001792111111111], + ["square yard", "yd2", ["yd^2"], "area", false, true, 0.83612736], + ["statute mile", "mi", null, "length", false, true, 1609.344], + ["steradian", "sr", null, "solid_angle", true, false, 1], + ["stilb", "sb", null, "luminance", false, false, 0.0001], + ["stokes", "St", null, "kinematic_viscosity", false, false, 0.0001], + ["stone", "stone", null, "mass", false, true, 6.35029318], + ["tablespoon", "tbs", null, "volume", false, true, 0.0000147868], + ["teaspoon", "tsp", null, "volume", false, true, 0.00000492892], + ["tesla", "T", null, "magnetic_flux_density", true, true, 1], + ["thermodynamic calorie", "c", null, "energy", false, true, 4.184], + ["ton", "ton", null, "mass", false, true, 907.18474], + ["tonne", "t", null, "mass", false, false, 1000], + ["U.K. pint", "uk_pt", null, "volume", false, true, 0.00056826125], + ["U.S. bushel", "bushel", null, "volume", false, true, 0.03523907], + ["U.S. oil barrel", "barrel", null, "volume", false, true, 0.158987295], + ["U.S. pint", "pt", ["us_pt"], "volume", false, true, 0.000473176473], + ["U.S. survey mile", "survey_mi", null, "length", false, true, 1609.347219], + ["U.S. survey/statute acre", "us_acre", null, "area", false, true, 4046.87261], + ["volt", "V", null, "voltage", true, false, 1], + ["watt", "W", null, "power", true, true, 1], + ["watt-hour", "Wh", ["wh"], "energy", false, true, 3600], + ["weber", "Wb", null, "magnetic_flux", true, false, 1], + ["yard", "yd", null, "length", false, true, 0.9144], + ["year", "yr", null, "time", false, true, 31557600] + ]; + + // Binary prefixes + // [Name, Prefix power of 2 value, Previx value, Abbreviation, Derived from] + var binary_prefixes = { + Yi: ["yobi", 80, 1208925819614629174706176, "Yi", "yotta"], + Zi: ["zebi", 70, 1180591620717411303424, "Zi", "zetta"], + Ei: ["exbi", 60, 1152921504606846976, "Ei", "exa"], + Pi: ["pebi", 50, 1125899906842624, "Pi", "peta"], + Ti: ["tebi", 40, 1099511627776, "Ti", "tera"], + Gi: ["gibi", 30, 1073741824, "Gi", "giga"], + Mi: ["mebi", 20, 1048576, "Mi", "mega"], + ki: ["kibi", 10, 1024, "ki", "kilo"] + }; + + // Unit prefixes + // [Name, Multiplier, Abbreviation] + var unit_prefixes = { + Y: ["yotta", 1e+24, "Y"], + Z: ["zetta", 1e+21, "Z"], + E: ["exa", 1e+18, "E"], + P: ["peta", 1e+15, "P"], + T: ["tera", 1e+12, "T"], + G: ["giga", 1e+09, "G"], + M: ["mega", 1e+06, "M"], + k: ["kilo", 1e+03, "k"], + h: ["hecto", 1e+02, "h"], + e: ["dekao", 1e+01, "e"], + d: ["deci", 1e-01, "d"], + c: ["centi", 1e-02, "c"], + m: ["milli", 1e-03, "m"], + u: ["micro", 1e-06, "u"], + n: ["nano", 1e-09, "n"], + p: ["pico", 1e-12, "p"], + f: ["femto", 1e-15, "f"], + a: ["atto", 1e-18, "a"], + z: ["zepto", 1e-21, "z"], + y: ["yocto", 1e-24, "y"] + }; + + // Initialize units and multipliers + var from = null; + var to = null; + var base_from_unit = from_unit; + var base_to_unit = to_unit; + var from_multiplier = 1; + var to_multiplier = 1; + var alt; + + // Lookup from and to units + for (var i = 0; i < units.length; i++) { + alt = (units[i][2] === null) ? [] : units[i][2]; + if (units[i][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) { + from = units[i]; + } + if (units[i][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) { + to = units[i]; + } + } + + // Lookup from prefix + if (from === null) { + var from_binary_prefix = binary_prefixes[from_unit.substring(0, 2)]; + var from_unit_prefix = unit_prefixes[from_unit.substring(0, 1)]; + + // Handle dekao unit prefix (only unit prefix with two characters) + if (from_unit.substring(0, 2) === 'da') { + from_unit_prefix = ["dekao", 1e+01, "da"]; + } + + // Handle binary prefixes first (so that 'Yi' is processed before 'Y') + if (from_binary_prefix) { + from_multiplier = from_binary_prefix[2]; + base_from_unit = from_unit.substring(2); + } else if (from_unit_prefix) { + from_multiplier = from_unit_prefix[1]; + base_from_unit = from_unit.substring(from_unit_prefix[2].length); + } + + // Lookup from unit + for (var j = 0; j < units.length; j++) { + alt = (units[j][2] === null) ? [] : units[j][2]; + if (units[j][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) { + from = units[j]; + } + } + } + + // Lookup to prefix + if (to === null) { + var to_binary_prefix = binary_prefixes[to_unit.substring(0, 2)]; + var to_unit_prefix = unit_prefixes[to_unit.substring(0, 1)]; + + // Handle dekao unit prefix (only unit prefix with two characters) + if (to_unit.substring(0, 2) === 'da') { + to_unit_prefix = ["dekao", 1e+01, "da"]; + } + + // Handle binary prefixes first (so that 'Yi' is processed before 'Y') + if (to_binary_prefix) { + to_multiplier = to_binary_prefix[2]; + base_to_unit = to_unit.substring(2); + } else if (to_unit_prefix) { + to_multiplier = to_unit_prefix[1]; + base_to_unit = to_unit.substring(to_unit_prefix[2].length); + } + + // Lookup to unit + for (var k = 0; k < units.length; k++) { + alt = (units[k][2] === null) ? [] : units[k][2]; + if (units[k][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) { + to = units[k]; + } + } + } + + // Return error if a unit does not exist + if (from === null || to === null) { + return '#N/A'; + } + + // Return error if units represent different quantities + if (from[3] !== to[3]) { + return '#N/A'; + } + + // Return converted number + return number * from[6] * from_multiplier / (to[6] * to_multiplier); + }; + + Formula.DEC2BIN = function (number, places) { + // Return error if number is not a number + if (isNaN(number)) { + return '#VALUE!'; + } + + // Return error if number is not decimal, is lower than -512, or is greater than 511 + if (!/^-?[0-9]{1,3}$/.test(number) || number < -512 || number > 511) { + return '#NUM!'; + } + + // Ignore places and return a 10-character binary number if number is negative + if (number < 0) { + return '1' + _s.repeat('0', 9 - (512 + number).toString(2).length) + (512 + number).toString(2); + } + + // Convert decimal number to binary + var result = parseInt(number, 10).toString(2); + + // Return binary number using the minimum number of characters necessary if places is undefined + if (typeof places === 'undefined') { + return result; + } else { + // Return error if places is nonnumeric + if (isNaN(places)) { + return '#VALUE!'; + } + + // Return error if places is negative + if (places < 0) { + return '#NUM!'; + } + + // Truncate places in case it is not an integer + places = Math.floor(places); + + // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) + return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; + } + }; + + Formula.DEC2HEX = function (number, places) { + // Return error if number is not a number + if (isNaN(number)) { + return '#VALUE!'; + } + + // Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887 + if (!/^-?[0-9]{1,12}$/.test(number) || number < -549755813888 || number > 549755813887) { + return '#NUM!'; + } + + // Ignore places and return a 10-character hexadecimal number if number is negative + if (number < 0) { + return (1099511627776 + number).toString(16); + } + + // Convert decimal number to hexadecimal + var result = parseInt(number, 10).toString(16); + + // Return hexadecimal number using the minimum number of characters necessary if places is undefined + if (typeof places === 'undefined') { + return result; + } else { + // Return error if places is nonnumeric + if (isNaN(places)) { + return '#VALUE!'; + } + + // Return error if places is negative + if (places < 0) { + return '#NUM!'; + } + + // Truncate places in case it is not an integer + places = Math.floor(places); + + // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) + return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; + } + }; + + Formula.DEC2OCT = function (number, places) { + // Return error if number is not a number + if (isNaN(number)) { + return '#VALUE!'; + } + + // Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887 + if (!/^-?[0-9]{1,9}$/.test(number) || number < -536870912 || number > 536870911) { + return '#NUM!'; + } + + // Ignore places and return a 10-character octal number if number is negative + if (number < 0) { + return (1073741824 + number).toString(8); + } + + // Convert decimal number to octal + var result = parseInt(number, 10).toString(8); + + // Return octal number using the minimum number of characters necessary if places is undefined + if (typeof places === 'undefined') { + return result; + } else { + // Return error if places is nonnumeric + if (isNaN(places)) { + return '#VALUE!'; + } + + // Return error if places is negative + if (places < 0) { + return '#NUM!'; + } + + // Truncate places in case it is not an integer + places = Math.floor(places); + + // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) + return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; + } + }; + + Formula.DELTA = function (number1, number2) { + // Set number2 to zero if undefined + number2 = (typeof number2 === 'undefined') ? 0 : number2; + + // Return error if either number is not a number + if (isNaN(number1) || isNaN(number2)) { + return '#VALUE!'; + } + + // Return delta + return (number1 === number2) ? 1 : 0; + }; + + Formula.ERF = function (lower_bound, upper_bound) { + // Set number2 to zero if undefined + upper_bound = (typeof upper_bound === 'undefined') ? 0 : upper_bound; + + // Return error if either number is not a number + if (isNaN(lower_bound) || isNaN(upper_bound)) { + return '#VALUE!'; + } + + // Return ERFC using jStat [http://www.jstat.org/] + return jStat.erf(lower_bound); + }; + + Formula.ERFC = function (x) { + // Return error if x is not a number + if (isNaN(x)) { + return '#VALUE!'; + } + + // Return ERFC using jStat [http://www.jstat.org/] + return jStat.erfc(x); + }; + + Formula.ERFCPRECISE = function () { + return; + }; + + Formula.ERFPRECISE = function () { + return; + }; + + Formula.GESTEP = function (number, step) { + // Set step to zero if undefined + step = (typeof step === 'undefined') ? 0 : step; + + // Return error if either number is not a number + if (isNaN(number) || isNaN(step)) { + return '#VALUE!'; + } + + // Return delta + return (number >= step) ? 1 : 0; + }; + + Formula.HEX2BIN = function (number, places) { + + // Return error if number is not hexadecimal or contains more than ten characters (10 digits) + if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { + return '#NUM!'; + } + + // Check if number is negative + var negative = (number.length === 10 && number.substring(0, 1).toLowerCase() === 'f') ? true : false; + + // Convert hexadecimal number to decimal + var decimal = (negative) ? parseInt(number, 16) - 1099511627776 : parseInt(number, 16); + + // Return error if number is lower than -512 or greater than 511 + if (decimal < -512 || decimal > 511) { + return '#NUM!'; + } + + // Ignore places and return a 10-character binary number if number is negative + if (negative) { + return '1' + _s.repeat('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2); + } + + // Convert decimal number to binary + var result = decimal.toString(2); + + // Return binary number using the minimum number of characters necessary if places is undefined + if (typeof places === 'undefined') { + return result; + } else { + // Return error if places is nonnumeric + if (isNaN(places)) { + return '#VALUE!'; + } + + // Return error if places is negative + if (places < 0) { + return '#NUM!'; + } + + // Truncate places in case it is not an integer + places = Math.floor(places); + + // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) + return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; + } + }; + + Formula.HEX2DEC = function (number) { + // Return error if number is not hexadecimal or contains more than ten characters (10 digits) + if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { + return '#NUM!'; + } + + // Convert hexadecimal number to decimal + var decimal = parseInt(number, 16); + + // Return decimal number + return (decimal >= 549755813888) ? decimal - 1099511627776 : decimal; + }; + + Formula.HEX2OCT = function (number, places) { + // Return error if number is not hexadecimal or contains more than ten characters (10 digits) + if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { + return '#NUM!'; + } + + // Convert hexadecimal number to decimal + var decimal = parseInt(number, 16); + + // Return error if number is positive and greater than 0x1fffffff (536870911) + if (decimal > 536870911 && decimal < 1098974756864) { + return '#NUM!'; + } + + // Ignore places and return a 10-character octal number if number is negative + if (decimal >= 1098974756864) { + return (decimal - 1098437885952).toString(8); + } + + // Convert decimal number to octal + var result = decimal.toString(8); + + // Return octal number using the minimum number of characters necessary if places is undefined + if (typeof places === 'undefined') { + return result; + } else { + // Return error if places is nonnumeric + if (isNaN(places)) { + return '#VALUE!'; + } + + // Return error if places is negative + if (places < 0) { + return '#NUM!'; + } + + // Truncate places in case it is not an integer + places = Math.floor(places); + + // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) + return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; + } + }; + + Formula.IMABS = function (inumber) { + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return absolute value of complex number + return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); + }; + + Formula.IMAGINARY = function (inumber) { + // Return 0 if inumber is equal to 0 + if (inumber === 0 || inumber === '0') { + return 0; + } + + // Handle special cases + if (['i', 'j'].indexOf(inumber) >= 0) { + return 1; + } + + // Normalize imaginary coefficient + inumber = inumber.replace('+i', '+1i').replace('-i', '-1i').replace('+j', '+1j').replace('-j', '-1j'); + + // Lookup sign + var plus = inumber.indexOf('+'); + var minus = inumber.indexOf('-'); + if (plus === 0) { + plus = inumber.indexOf('+', 1); + } + + if (minus === 0) { + minus = inumber.indexOf('-', 1); + } + + // Lookup imaginary unit + var last = inumber.substring(inumber.length - 1, inumber.length); + var unit = (last === 'i' || last === 'j'); + + if (plus >= 0 || minus >= 0) { + // Return error if imaginary unit is neither i nor j + if (!unit) { + return '#NUM!'; + } + + // Return imaginary coefficient of complex number + if (plus >= 0) { + return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? + '#NUM!' : + Number(inumber.substring(plus + 1, inumber.length - 1)); + } else { + return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? + '#NUM!' : + -Number(inumber.substring(minus + 1, inumber.length - 1)); + } + } else { + if (unit) { + return (isNaN(inumber.substring(0, inumber.length - 1))) ? '#NUM!' : inumber.substring(0, inumber.length - 1); + } else { + return (isNaN(inumber)) ? '#NUM!' : 0; + } + } + }; + + Formula.IMARGUMENT = function (inumber) { + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return error if inumber is equal to zero + if (x === 0 && y === 0) { + return '#DIV/0!'; + } + + // Return PI/2 if x is equal to zero and y is positive + if (x === 0 && y > 0) { + return Math.PI / 2; + } + + // Return -PI/2 if x is equal to zero and y is negative + if (x === 0 && y < 0) { + return -Math.PI / 2; + } + + // Return zero if x is negative and y is equal to zero + if (y === 0 && x > 0) { + return 0; + } + + // Return zero if x is negative and y is equal to zero + if (y === 0 && x < 0) { + return -Math.PI; + } + + // Return argument of complex number + if (x > 0) { + return Math.atan(y / x); + } else if (x < 0 && y >= 0) { + return Math.atan(y / x) + Math.PI; + } else { + return Math.atan(y / x) - Math.PI; + } + }; + + Formula.IMCONJUGATE = function (inumber) { + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return conjugate of complex number + return (y !== 0) ? Formula.COMPLEX(x, -y, unit) : inumber; + }; + + Formula.IMCOS = function (inumber) { + // Return error if inumber is a logical value + if (inumber === true || inumber === false) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return cosine of complex number + return Formula.COMPLEX(Math.cos(x) * (Math.exp(y) + Math.exp(-y)) / 2, -Math.sin(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit); + }; + + Formula.IMCOSH = function (inumber) { + // Return error if inumber is a logical value + if (inumber === true || inumber === false) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return hyperbolic cosine of complex number + return Formula.COMPLEX(Math.cos(y) * (Math.exp(x) + Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) - Math.exp(-x)) / 2, unit); + }; + + Formula.IMCOT = function (inumber) { + // Return error if inumber is a logical value + if (inumber === true || inumber === false) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return cotangent of complex number + return Formula.IMDIV(Formula.IMCOS(inumber), Formula.IMSIN(inumber)); + }; + + Formula.IMCSC = function (inumber) { + // Return error if inumber is a logical value + if (inumber === true || inumber === false) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return cosecant of complex number + return Formula.IMDIV('1', Formula.IMSIN(inumber)); + }; + + Formula.IMCSCH = function (inumber) { + // Return error if inumber is a logical value + if (inumber === true || inumber === false) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return hyperbolic cosecant of complex number + return Formula.IMDIV('1', Formula.IMSINH(inumber)); + }; + + Formula.IMDIV = function (inumber1, inumber2) { + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var a = Formula.IMREAL(inumber1); + var b = Formula.IMAGINARY(inumber1); + var c = Formula.IMREAL(inumber2); + var d = Formula.IMAGINARY(inumber2); + + // Lookup imaginary unit + var unit1 = inumber1.substring(inumber1.length - 1); + var unit2 = inumber1.substring(inumber1.length - 1); + var unit = 'i'; + if (unit1 === 'j') { + unit = 'j'; + } else if (unit2 === 'j') { + unit = 'j'; + } + + // Return error if either coefficient is not a number + if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { + return '#NUM!'; + } + + // Return error if inumber2 is null + if (c === 0 && d === 0) { + return '#NUM!'; + } + + // Return exponential of complex number + var den = c * c + d * d; + return Formula.COMPLEX((a * c + b * d) / den, (b * c - a * d) / den, unit); + }; + + Formula.IMEXP = function (inumber) { + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return exponential of complex number + var e = Math.exp(x); + return Formula.COMPLEX(e * Math.cos(y), e * Math.sin(y), unit); + }; + + Formula.IMLN = function (inumber) { + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return exponential of complex number + return Formula.COMPLEX(Math.log(Math.sqrt(x * x + y * y)), Math.atan(y / x), unit); + }; + + Formula.IMLOG10 = function (inumber) { + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return exponential of complex number + return Formula.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(10), Math.atan(y / x) / Math.log(10), unit); + }; + + Formula.IMLOG2 = function (inumber) { + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return exponential of complex number + return Formula.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(2), Math.atan(y / x) / Math.log(2), unit); + }; + + Formula.IMPOWER = function (inumber, number) { + // Return error if number is nonnumeric + if (isNaN(number)) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Calculate power of modulus + var p = Math.pow(Formula.IMABS(inumber), number); + + // Calculate argument + var t = Formula.IMARGUMENT(inumber); + + // Return exponential of complex number + return Formula.COMPLEX(p * Math.cos(number * t), p * Math.sin(number * t), unit); + }; + + Formula.IMPRODUCT = function () { + // Initialize result + var result = arguments[0]; + + // Loop on all numbers + for (var i = 1; i < arguments.length; i++) { + // Lookup coefficients of two complex numbers + var a = Formula.IMREAL(result); + var b = Formula.IMAGINARY(result); + var c = Formula.IMREAL(arguments[i]); + var d = Formula.IMAGINARY(arguments[i]); + + // Return error if either coefficient is not a number + if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { + return '#NUM!'; + } + + // Complute product of two complex numbers + result = Formula.COMPLEX(a * c - b * d, a * d + b * c); + } + + // Return product of complex numbers + return result; + }; + + Formula.IMREAL = function (inumber) { + // Return 0 if inumber is equal to 0 + if (inumber === 0 || inumber === '0') { + return 0; + } + + // Handle special cases + if (['i', '+i', '1i', '+1i', '-i', '-1i', 'j', '+j', '1j', '+1j', '-j', '-1j'].indexOf(inumber) >= 0) { + return 0; + } + + // Lookup sign + var plus = inumber.indexOf('+'); + var minus = inumber.indexOf('-'); + if (plus === 0) { + plus = inumber.indexOf('+', 1); + } + if (minus === 0) { + minus = inumber.indexOf('-', 1); + } + + // Lookup imaginary unit + var last = inumber.substring(inumber.length - 1, inumber.length); + var unit = (last === 'i' || last === 'j'); + + if (plus >= 0 || minus >= 0) { + // Return error if imaginary unit is neither i nor j + if (!unit) { + return '#NUM!'; + } + + // Return real coefficient of complex number + if (plus >= 0) { + return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? + '#NUM!' : + Number(inumber.substring(0, plus)); + } else { + return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? + '#NUM!' : + Number(inumber.substring(0, minus)); + } + } else { + if (unit) { + return (isNaN(inumber.substring(0, inumber.length - 1))) ? '#NUM!' : 0; + } else { + return (isNaN(inumber)) ? '#NUM!' : inumber; + } + } + }; + + Formula.IMSEC = function (inumber) { + // Return error if inumber is a logical value + if (inumber === true || inumber === false) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return secant of complex number + return Formula.IMDIV('1', Formula.IMCOS(inumber)); + }; + + Formula.IMSECH = function (inumber) { + // Return error if inumber is a logical value + if (inumber === true || inumber === false) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return hyperbolic secant of complex number + return Formula.IMDIV('1', Formula.IMCOSH(inumber)); + }; + + Formula.IMSIN = function (inumber) { + // Return error if inumber is a logical value + if (inumber === true || inumber === false) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return sine of complex number + return Formula.COMPLEX(Math.sin(x) * (Math.exp(y) + Math.exp(-y)) / 2, Math.cos(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit); + }; + + Formula.IMSINH = function (inumber) { + // Return error if inumber is a logical value + if (inumber === true || inumber === false) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return hyperbolic sine of complex number + return Formula.COMPLEX(Math.cos(y) * (Math.exp(x) - Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) + Math.exp(-x)) / 2, unit); + }; + + Formula.IMSQRT = function (inumber) { + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Lookup imaginary unit + var unit = inumber.substring(inumber.length - 1); + unit = (unit === 'i' || unit === 'j') ? unit : 'i'; + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Calculate power of modulus + var s = Math.sqrt(Formula.IMABS(inumber)); + + // Calculate argument + var t = Formula.IMARGUMENT(inumber); + + // Return exponential of complex number + return Formula.COMPLEX(s * Math.cos(t / 2), s * Math.sin(t / 2), unit); + }; + + Formula.IMSUB = function (inumber1, inumber2) { + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var a = Formula.IMREAL(inumber1); + var b = Formula.IMAGINARY(inumber1); + var c = Formula.IMREAL(inumber2); + var d = Formula.IMAGINARY(inumber2); + + // Lookup imaginary unit + var unit1 = inumber1.substring(inumber1.length - 1); + var unit2 = inumber1.substring(inumber1.length - 1); + var unit = 'i'; + if (unit1 === 'j') { + unit = 'j'; + } else if (unit2 === 'j') { + unit = 'j'; + } + + // Return error if either coefficient is not a number + if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { + return '#NUM!'; + } + + // Return _ of two complex numbers + return Formula.COMPLEX(a - c, b - d, unit); + }; + + Formula.IMSUM = function () { + // Initialize result + var result = arguments[0]; + + // Loop on all numbers + for (var i = 1; i < arguments.length; i++) { + // Lookup coefficients of two complex numbers + var a = Formula.IMREAL(result); + var b = Formula.IMAGINARY(result); + var c = Formula.IMREAL(arguments[i]); + var d = Formula.IMAGINARY(arguments[i]); + + // Return error if either coefficient is not a number + if (a === '#NUM!' || b === '#NUM!' || c === '#NUM!' || d === '#NUM!') { + return '#NUM!'; + } + + // Complute product of two complex numbers + result = Formula.COMPLEX(a + c, b + d); + } + + // Return sum of complex numbers + return result; + }; + + Formula.IMTAN = function (inumber) { + // Return error if inumber is a logical value + if (inumber === true || inumber === false) { + return '#VALUE!'; + } + + // Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] + var x = Formula.IMREAL(inumber); + var y = Formula.IMAGINARY(inumber); + + // Return error if either coefficient is not a number + if (x === '#NUM!' || y === '#NUM!') { + return '#NUM!'; + } + + // Return tangent of complex number + return Formula.IMDIV(Formula.IMSIN(inumber), Formula.IMCOS(inumber)); + }; + + Formula.OCT2BIN = function (number, places) { + // Return error if number is not hexadecimal or contains more than ten characters (10 digits) + if (!/^[0-7]{1,10}$/.test(number)) { + return '#NUM!'; + } + + // Check if number is negative + var negative = (number.length === 10 && number.substring(0, 1) === '7') ? true : false; + + // Convert octal number to decimal + var decimal = (negative) ? parseInt(number, 8) - 1073741824 : parseInt(number, 8); + + // Return error if number is lower than -512 or greater than 511 + if (decimal < -512 || decimal > 511) { + return '#NUM!'; + } + + // Ignore places and return a 10-character binary number if number is negative + if (negative) { + return '1' + _s.repeat('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2); + } + + // Convert decimal number to binary + var result = decimal.toString(2); + + // Return binary number using the minimum number of characters necessary if places is undefined + if (typeof places === 'undefined') { + return result; + } else { + // Return error if places is nonnumeric + if (isNaN(places)) { + return '#VALUE!'; + } + + // Return error if places is negative + if (places < 0) { + return '#NUM!'; + } + + // Truncate places in case it is not an integer + places = Math.floor(places); + + // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) + return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; + } + }; + + Formula.OCT2DEC = function (number) { + // Return error if number is not octal or contains more than ten characters (10 digits) + if (!/^[0-7]{1,10}$/.test(number)) { + return '#NUM!'; + } + + // Convert octal number to decimal + var decimal = parseInt(number, 8); + + // Return decimal number + return (decimal >= 536870912) ? decimal - 1073741824 : decimal; + }; + + Formula.OCT2HEX = function (number, places) { + // Return error if number is not octal or contains more than ten characters (10 digits) + if (!/^[0-7]{1,10}$/.test(number)) { + return '#NUM!'; + } + + // Convert octal number to decimal + var decimal = parseInt(number, 8); + + // Ignore places and return a 10-character octal number if number is negative + if (decimal >= 536870912) { + return 'ff' + (decimal + 3221225472).toString(16); + } + + // Convert decimal number to hexadecimal + var result = decimal.toString(16); + + // Return hexadecimal number using the minimum number of characters necessary if places is undefined + if (typeof places === 'undefined') { + return result; + } else { + // Return error if places is nonnumeric + if (isNaN(places)) { + return '#VALUE!'; + } + + // Return error if places is negative + if (places < 0) { + return '#NUM!'; + } + + // Truncate places in case it is not an integer + places = Math.floor(places); + + // Pad return value with leading 0s (zeros) if necessary (using Underscore.string) + return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!'; + } + }; + + + // Financial functions + + Formula.ACCRINT = function (issue, first, settlement, rate, par, frequency, basis, method) { + // Return error if either date is invalid + if (!moment(issue).isValid() || !moment(first).isValid() || !moment(settlement).isValid()) { + return '#VALUE!'; + } + + // Return error if either rate or par are lower than or equal to zero + if (rate <= 0 || par <= 0) { + return '#NUM!'; + } + + // Return error if frequency is neither 1, 2, or 4 + if ([1, 2, 4].indexOf(frequency) === -1) { + return '#NUM!'; + } + + // Return error if basis is neither 0, 1, 2, 3, or 4 + if ([0, 1, 2, 3, 4].indexOf(basis) === -1) { + return '#NUM!'; + } + + // Return error if issue greater than or equal to settlement + if (moment(issue).diff(moment(settlement)) >= 0) { + return '#NUM!'; + } + + // Set default values + par = (typeof par === 'undefined') ? 0 : par; + basis = (typeof basis === 'undefined') ? 0 : basis; + method = (typeof method === 'undefined') ? true : method; + + // Compute accrued interest + var factor = 0; + switch (basis) { + case 0: + // US (NASD) 30/360 + factor = Formula.YEARFRAC(issue, settlement, basis); + break; + case 1: + // Actual/actual + factor = Formula.YEARFRAC(issue, settlement, basis); + break; + case 2: + // Actual/360 + factor = Formula.YEARFRAC(issue, settlement, basis); + break; + case 3: + // Actual/365 + factor = Formula.YEARFRAC(issue, settlement, basis); + break; + case 4: + // European 30/360 + factor = Formula.YEARFRAC(issue, settlement, basis); + break; + } + return par * rate * factor; + }; + + Formula.ACCRINTM = function () { + return; + }; + + Formula.AMORDEGRC = function () { + return; + }; + + Formula.AMORLINC = function () { + return; + }; + + Formula.COUPDAYBS = function () { + return; + }; + + Formula.COUPDAYS = function () { + return; + }; + + Formula.COUPDAYSNC = function () { + return; + }; + + Formula.COUPNCD = function () { + return; + }; + + Formula.COUPNUM = function () { + return; + }; + + Formula.COUPPCD = function () { + return; + }; + + Formula.CUMIPMT = function (rate, periods, value, start, end, type) { + // Credits: algorithm inspired by Apache OpenOffice + // Credits: Hannes Stiebitzhofer for the translations of function and variable names + // Requires Formula.FV() and Formula.PMT() from Formula.js [http://stoic.com/formula/] + + // Evaluate rate and periods (TODO: replace with secure expression evaluator) + rate = eval(rate); + periods = eval(periods); + + // Return error if either rate, periods, or value are lower than or equal to zero + if (rate <= 0 || periods <= 0 || value <= 0) { + return '#NUM!'; + } + + // Return error if start < 1, end < 1, or start > end + if (start < 1 || end < 1 || start > end) { + return '#NUM!'; + } + + // Return error if type is neither 0 nor 1 + if (type !== 0 && type !== 1) { + return '#NUM!'; + } + + // Compute cumulative interest + var payment = Formula.PMT(rate, periods, value, 0, type); + var interest = 0; + + if (start === 1) { + if (type === 0) { + interest = -value; + start++; + } + } + + for (var i = start; i <= end; i++) { + if (type === 1) { + interest += Formula.FV(rate, i - 2, payment, value, 1) - payment; + } else { + interest += Formula.FV(rate, i - 1, payment, value, 0); + } + } + interest *= rate; + + // Return cumulative interest + return interest; + }; + + Formula.CUMPRINC = function (rate, periods, value, start, end, type) { + // Credits: algorithm inspired by Apache OpenOffice + // Credits: Hannes Stiebitzhofer for the translations of function and variable names + // Requires Formula.FV() and Formula.PMT() from Formula.js [http://stoic.com/formula/] + + // Evaluate rate and periods (TODO: replace with secure expression evaluator) + rate = eval(rate); + periods = eval(periods); + + // Return error if either rate, periods, or value are lower than or equal to zero + if (rate <= 0 || periods <= 0 || value <= 0) { + return '#NUM!'; + } + + // Return error if start < 1, end < 1, or start > end + if (start < 1 || end < 1 || start > end) { + return '#NUM!'; + } + + // Return error if type is neither 0 nor 1 + if (type !== 0 && type !== 1) { + return '#NUM!'; + } + + // Compute cumulative principal + var payment = Formula.PMT(rate, periods, value, 0, type); + var principal = 0; + if (start === 1) { + if (type === 0) { + principal = payment + value * rate; + } else { + principal = payment; + } + start++; + } + for (var i = start; i <= end; i++) { + if (type > 0) { + principal += payment - (Formula.FV(rate, i - 2, payment, value, 1) - payment) * rate; + } else { + principal += payment - Formula.FV(rate, i - 1, payment, value, 0) * rate; + } + } + + // Return cumulative principal + return principal; + }; + + Formula.DB = function (cost, salvage, life, period, month) { + // Initialize month + month = (typeof month === 'undefined') ? 12 : month; + + // Return error if any of the parameters is not a number + if (isNaN(cost) || isNaN(salvage) || isNaN(life) || isNaN(period) || isNaN(month)) { + return '#VALUE!'; + } + + // Return error if any of the parameters is negative [ + + if (cost < 0 || salvage < 0 || life < 0 || period < 0) { + return '#NUM!'; + } + + // Return error if month is not an integer between 1 and 12 + if ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].indexOf(month) === -1) { + return '#NUM!'; + } + + // Return error if period is greater than life + if (period > life) { + return '#NUM!'; + } + + // Return 0 (zero) if salvage is greater than or equal to cost + if (salvage >= cost) { + return 0; + } + + // Rate is rounded to three decimals places + var rate = (1 - Math.pow(salvage / cost, 1 / life)).toFixed(3); + + // Compute initial depreciation + var initial = cost * rate * month / 12; + + // Compute total depreciation + var total = initial; + var current = 0; + var ceiling = (period === life) ? life - 1 : period; + for (var i = 2; i <= ceiling; i++) { + current = (cost - total) * rate; + total += current; + } + + // Depreciation for the first and last periods are special cases + if (period === 1) { + // First period + return initial; + } else if (period === life) { + // Last period + return (cost - total) * rate; + } else { + return current; + } + }; + + Formula.DDB = function (cost, salvage, life, period, factor) { + // Initialize factor + factor = (typeof factor === 'undefined') ? 2 : factor; + + // Return error if any of the parameters is not a number + if (isNaN(cost) || isNaN(salvage) || isNaN(life) || isNaN(period) || isNaN(factor)) { + return '#VALUE!'; + } + + // Return error if any of the parameters is negative or if factor is null + if (cost < 0 || salvage < 0 || life < 0 || period < 0 || factor <= 0) { + return '#NUM!'; + } + + // Return error if period is greater than life + if (period > life) { + return '#NUM!'; + } + + // Return 0 (zero) if salvage is greater than or equal to cost + if (salvage >= cost) { + return 0; + } + + // Compute depreciation + var total = 0; + var current = 0; + for (var i = 1; i <= period; i++) { + current = Math.min((cost - total) * (factor / life), (cost - salvage - total)); + total += current; + } + + // Return depreciation + return current; + }; + + Formula.DISC = function () { + return; + }; + + Formula.DOLLARDE = function (dollar, fraction) { + // Credits: algorithm inspired by Apache OpenOffice + + // Return error if any of the parameters is not a number + if (isNaN(dollar) || isNaN(fraction)) { + return '#VALUE!'; + } + + // Return error if fraction is negative + if (fraction < 0) { + return '#NUM!'; + } + + // Return error if fraction is greater than or equal to 0 and less than 1 + if (fraction >= 0 && fraction < 1) { + return '#DIV/0!'; + } + + // Truncate fraction if it is not an integer + fraction = parseInt(fraction, 10); + + // Compute integer part + var result = parseInt(dollar, 10); + + // Add decimal part + result += (dollar % 1) * Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN10)) / fraction; + + // Round result + var power = Math.pow(10, Math.ceil(Math.log(fraction) / Math.LN2) + 1); + result = Math.round(result * power) / power; + + // Return converted dollar price + return result; + }; + + Formula.DOLLARFR = function (dollar, fraction) { + // Credits: algorithm inspired by Apache OpenOffice + + // Return error if any of the parameters is not a number + if (isNaN(dollar) || isNaN(fraction)) { + return '#VALUE!'; + } + + // Return error if fraction is negative + if (fraction < 0) { + return '#NUM!'; + } + + // Return error if fraction is greater than or equal to 0 and less than 1 + if (fraction >= 0 && fraction < 1) { + return '#DIV/0!'; + } + + // Truncate fraction if it is not an integer + fraction = parseInt(fraction, 10); + + // Compute integer part + var result = parseInt(dollar, 10); + + // Add decimal part + result += (dollar % 1) * Math.pow(10, -Math.ceil(Math.log(fraction) / Math.LN10)) * fraction; + + // Return converted dollar price + return result; + }; + + Formula.DURATION = function () { + return; + }; + + Formula.EFFECT = function (rate, periods) { + // Return error if any of the parameters is not a number + if (isNaN(rate) || isNaN(periods)) { + return '#VALUE!'; + } + + // Return error if rate <=0 or periods < 1 + if (rate <= 0 || periods < 1) { + return '#NUM!'; + } + + // Truncate periods if it is not an integer + periods = parseInt(periods, 10); + + // Return effective annual interest rate + return Math.pow(1 + rate / periods, periods) - 1; + }; + + Formula.FV = function (rate, periods, payment, value, type) { + // Credits: algorithm inspired by Apache OpenOffice + + // Initialize type + type = (typeof type === 'undefined') ? 0 : type; + + // Evaluate rate (TODO: replace with secure expression evaluator) + rate = eval(rate); + + // Return future value + var result; + if (rate === 0) { + result = value + payment * periods; + } else { + var term = Math.pow(1 + rate, periods); + if (type === 1) { + result = value * term + payment * (1 + rate) * (term - 1.0) / rate; + } else { + result = value * term + payment * (term - 1) / rate; + } + } + return -result; + }; + + Formula.FVSCHEDULE = function (principal, schedule) { + // Initialize future value + var future = principal; + + // Apply all interests in schedule + for (var i = 0; i < schedule.length; i++) { + // Return error if schedule value is not a number + if (isNaN(schedule[i])) { + return '#VALUE!'; + } + + // Apply scheduled interest + future *= 1 + schedule[i]; + } + + // Return future value + return future; + }; + + Formula.INTRATE = function () { + return; + }; + + Formula.IPMT = function (rate, period, periods, present, future, type) { + // Credits: algorithm inspired by Apache OpenOffice + + // Initialize type + type = (typeof type === 'undefined') ? 0 : type; + + // Evaluate rate and periods (TODO: replace with secure expression evaluator) + rate = eval(rate); + periods = eval(periods); + + // Compute payment + var payment = Formula.PMT(rate, periods, present, future, type); + + // Compute interest + var interest; + if (period === 1) { + if (type === 1) { + interest = 0; + } else { + interest = -present; + } + } else { + if (type === 1) { + interest = Formula.FV(rate, period - 2, payment, present, 1) - payment; + } else { + interest = Formula.FV(rate, period - 1, payment, present, 0); + } + } + + // Return interest + return interest * rate; + }; + + Formula.IRR = function (values, guess) { + // Credits: algorithm inspired by Apache OpenOffice + + // flatten so multi dimensional ranges also work + values = Formula.FLATTEN(values); + + // Calculates the resulting amount + var irrResult = function (values, dates, rate) { + var r = rate + 1; + var result = values[0]; + for (var i = 1; i < values.length; i++) { + result += values[i] / Math.pow(r, (dates[i] - dates[0]) / 365); + } + return result; + }; + + // Calculates the first derivation + var irrResultDeriv = function (values, dates, rate) { + var r = rate + 1; + var result = 0; + for (var i = 1; i < values.length; i++) { + var frac = (dates[i] - dates[0]) / 365; + result -= frac * values[i] / Math.pow(r, frac + 1); + } + return result; + }; + + // Initialize dates and check that values contains at least one positive value and one negative value + var dates = []; + var positive = false; + var negative = false; + for (var i = 0; i < values.length; i++) { + dates[i] = (i === 0) ? 0 : dates[i - 1] + 365; + if (values[i] > 0) { + positive = true; + } + if (values[i] < 0) { + negative = true; + } + } + + // Return error if values does not contain at least one positive value and one negative value + if (!positive || !negative) { + return '#NUM!'; + } + + // Initialize guess and resultRate + guess = (typeof guess === 'undefined') ? 0.1 : guess; + var resultRate = guess; + + // Set maximum epsilon for end of iteration + var epsMax = 1e-10; + + // Set maximum number of iterations + var iterMax = 50; + + // Implement Newton's method + var newRate, epsRate, resultValue; + var iteration = 0; + var contLoop = true; + do { + resultValue = irrResult(values, dates, resultRate); + newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate); + epsRate = Math.abs(newRate - resultRate); + resultRate = newRate; + contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax); + } while (contLoop && (++iteration < iterMax)); + + if (contLoop) { + return '#NUM!'; + } + + // Return internal rate of return + return resultRate; + }; + + Formula.ISPMT = function (rate, period, periods, value) { + // Evaluate rate and periods (TODO: replace with secure expression evaluator) + rate = eval(rate); + periods = eval(periods); + + // Return interest + return value * rate * (period / periods - 1); + }; + + Formula.MDURATION = function () { + return; + }; + + Formula.MIRR = function (values, finance_rate, reinvest_rate) { + // Initialize number of values + var n = values.length; + + // Lookup payments (negative values) and incomes (positive values) + var payments = []; + var incomes = []; + for (var i = 0; i < n; i++) { + if (values[i] < 0) { + payments.push(values[i]); + } else { + incomes.push(values[i]); + } + } + + // Return modified internal rate of return + var num = -Formula.NPV(reinvest_rate, incomes) * Math.pow(1 + reinvest_rate, n - 1); + var den = Formula.NPV(finance_rate, payments) * (1 + finance_rate); + return Math.pow(num / den, 1 / (n - 1)) - 1; + }; + + Formula.NOMINAL = function (rate, periods) { + // Return error if any of the parameters is not a number + if (isNaN(rate) || isNaN(periods)) { + return '#VALUE!'; + } + + // Return error if rate <=0 or periods < 1 + if (rate <= 0 || periods < 1) { + return '#NUM!'; + } + + // Truncate periods if it is not an integer + periods = parseInt(periods, 10); + + // Return nominal annual interest rate + return (Math.pow(rate + 1, 1 / periods) - 1) * periods; + }; + + Formula.NPER = function (rate, payment, present, future, type) { + // Initialize type + type = (typeof type === 'undefined') ? 0 : type; + + // Initialize future value + future = (typeof future === 'undefined') ? 0 : future; + + // Evaluate rate and periods (TODO: replace with secure expression evaluator) + rate = eval(rate); + + // Return number of periods + var num = payment * (1 + rate * type) - future * rate; + var den = (present * rate + payment * (1 + rate * type)); + return Math.log(num / den) / Math.log(1 + rate); + }; + + Formula.NPV = function () { + // Cast arguments to array + var args = []; + for (var i = 0; i < arguments.length; i++) { + args = args.concat(arguments[i]); + } + + // Lookup rate + var rate = args[0]; + + // Initialize net present value + var value = 0; + + // Loop on all values + for (var j = 1; j < args.length; j++) { + value += args[j] / Math.pow(1 + rate, j); + } + + // Return net present value + return value; + }; + + Formula.ODDFPRICE = function () { + return; + }; + + Formula.ODDFYIELD = function () { + return; + }; + + Formula.ODDLPRICE = function () { + return; + }; + + Formula.ODDLYIELD = function () { + return; + }; + + Formula.PDURATION = function (rate, present, future) { + // Return error if any of the parameters is not a number + if (isNaN(rate) || isNaN(present) || isNaN(future)) { + return '#VALUE!'; + } + + // Return error if rate <=0 + if (rate <= 0) { + return '#NUM!'; + } + + // Return number of periods + return (Math.log(future) - Math.log(present)) / Math.log(1 + rate); + }; + + Formula.PMT = function (rate, periods, present, future, type) { + // Credits: algorithm inspired by Apache OpenOffice + + // Initialize type + type = (typeof type === 'undefined') ? 0 : type; + + // Evaluate rate and periods (TODO: replace with secure expression evaluator) + rate = eval(rate); + periods = eval(periods); + + // Return payment + var result; + if (rate === 0) { + result = (present + future) / periods; + } else { + var term = Math.pow(1 + rate, periods); + if (type === 1) { + result = (future * rate / (term - 1) + present * rate / (1 - 1 / term)) / (1 + rate); + } else { + result = future * rate / (term - 1) + present * rate / (1 - 1 / term); + } + } + return -result; + }; + + Formula.PPMT = function (rate, period, periods, present, future, type) { + return Formula.PMT(rate, periods, present, future, type) - Formula.IPMT(rate, period, periods, present, future, type); + }; + + Formula.PRICE = function () { + return; + }; + + Formula.PRICEDISC = function () { + return; + }; + + Formula.PRICEMAT = function () { + return; + }; + + Formula.PV = function (rate, periods, payment, future, type) { + // Initialize type + type = (typeof type === 'undefined') ? 0 : type; + + // Evaluate rate and periods (TODO: replace with secure expression evaluator) + rate = eval(rate); + periods = eval(periods); + + // Return present value + if (rate === 0) { + return -payment * periods - future; + } else { + return (((1 - Math.pow(1 + rate, periods)) / rate) * payment * (1 + rate * type) - future) / Math.pow(1 + rate, periods); + } + }; + + Formula.RATE = function (periods, payment, present, future, type, guess) { + // Credits: rabugento + + // Initialize guess + guess = (typeof guess === 'undefined') ? 0.01 : guess; + + // Initialize future + future = (typeof future === 'undefined') ? 0 : future; + + // Initialize type + type = (typeof type === 'undefined') ? 0 : type; + + // Evaluate periods (TODO: replace with secure expression evaluator) + periods = eval(periods); + + // Set maximum epsilon for end of iteration + var epsMax = 1e-10; + + // Set maximum number of iterations + var iterMax = 50; + + // Implement Newton's method + var y, y0, y1, x0, x1 = 0, f = 0, i = 0; + var rate = guess; + if (Math.abs(rate) < epsMax) { + y = present * (1 + periods * rate) + payment * (1 + rate * type) * periods + future; + } else { + f = Math.exp(periods * Math.log(1 + rate)); + y = present * f + payment * (1 / rate + type) * (f - 1) + future; + } + y0 = present + payment * periods + future; + y1 = present * f + payment * (1 / rate + type) * (f - 1) + future; + i = x0 = 0; + x1 = rate; + while ((Math.abs(y0 - y1) > epsMax) && (i < iterMax)) { + rate = (y1 * x0 - y0 * x1) / (y1 - y0); + x0 = x1; + x1 = rate; + if (Math.abs(rate) < epsMax) { + y = present * (1 + periods * rate) + payment * (1 + rate * type) * periods + future; + } else { + f = Math.exp(periods * Math.log(1 + rate)); + y = present * f + payment * (1 / rate + type) * (f - 1) + future; + } + y0 = y1; + y1 = y; + ++i; + } + return rate; + }; + + Formula.RECEIVED = function () { + return; + }; + + Formula.RRI = function (periods, present, future) { + // Return error if any of the parameters is not a number + if (isNaN(periods) || isNaN(present) || isNaN(future)) { + return '#VALUE!'; + } + + // Return error if periods or present is equal to 0 (zero) + if (periods === 0 || present === 0) { + return '#NUM!'; + } + + // Return equivalent interest rate + return Math.pow(future / present, 1 / periods) - 1; + }; + + Formula.SLN = function (cost, salvage, life) { + // Return error if any of the parameters is not a number + if (isNaN(cost) || isNaN(salvage) || isNaN(life)) { + return '#VALUE!'; + } + + // Return error if life equal to 0 (zero) + if (life === 0) { + return '#NUM!'; + } + + // Return straight-line depreciation + return (cost - salvage) / life; + }; + + Formula.SYD = function (cost, salvage, life, period) { + // Return error if any of the parameters is not a number + if (isNaN(cost) || isNaN(salvage) || isNaN(life) || isNaN(period)) { + return '#VALUE!'; + } + + // Return error if life equal to 0 (zero) + if (life === 0) { + return '#NUM!'; + } + + // Return error if period is lower than 1 or greater than life + if (period < 1 || period > life) { + return '#NUM!'; + } + + // Truncate period if it is not an integer + period = parseInt(period, 10); + + // Return straight-line depreciation + return (cost - salvage) * (life - period + 1) * 2 / (life * (life + 1)); + }; + + Formula.TBILLEQ = function (settlement, maturity, discount) { + // Return error if either date is invalid + if (!moment(settlement).isValid() || !moment(maturity).isValid()) { + return '#VALUE!'; + } + + // Return error if discount is lower than or equal to zero + if (discount <= 0) { + return '#NUM!'; + } + + // Return error if settlement is greater than maturity + if (moment(settlement).diff(moment(maturity)) > 0) { + return '#NUM!'; + } + + // Return error if maturity is more than one year after settlement + if (moment(maturity).diff(moment(settlement), 'years') > 1) { + return '#NUM!'; + } + + // Return bond-equivalent yield + return (365 * discount) / (360 - discount * Formula.DAYS360(settlement, maturity)); + }; + + Formula.TBILLPRICE = function (settlement, maturity, discount) { + // Return error if either date is invalid + if (!moment(settlement).isValid() || !moment(maturity).isValid()) { + return '#VALUE!'; + } + + // Return error if discount is lower than or equal to zero + if (discount <= 0) { + return '#NUM!'; + } + + // Return error if settlement is greater than maturity + if (moment(settlement).diff(moment(maturity)) > 0) { + return '#NUM!'; + } + + // Return error if maturity is more than one year after settlement + if (moment(maturity).diff(moment(settlement), 'years') > 1) { + return '#NUM!'; + } + + // Return bond-equivalent yield + return 100 * (1 - discount * Formula.DAYS360(settlement, maturity) / 360); + }; + + Formula.TBILLYIELD = function (settlement, maturity, price) { + // Return error if either date is invalid + if (!moment(settlement).isValid() || !moment(maturity).isValid()) { + return '#VALUE!'; + } + + // Return error if price is lower than or equal to zero + if (price <= 0) { + return '#NUM!'; + } + + // Return error if settlement is greater than maturity + if (moment(settlement).diff(moment(maturity)) > 0) { + return '#NUM!'; + } + + // Return error if maturity is more than one year after settlement + if (moment(maturity).diff(moment(settlement), 'years') > 1) { + return '#NUM!'; + } + + // Return bond-equivalent yield + return (100 - price) * 360 / (price * Formula.DAYS360(settlement, maturity)); + }; + + Formula.VDB = function () { + return; + }; + + + Formula.XIRR = function (values, dates, guess) { + // Credits: algorithm inspired by Apache OpenOffice + + // Calculates the resulting amount + var irrResult = function (values, dates, rate) { + var r = rate + 1; + var result = values[0]; + for (var i = 1; i < values.length; i++) { + result += values[i] / Math.pow(r, moment(dates[i]).diff(moment(dates[0]), 'days') / 365); + } + return result; + }; + + // Calculates the first derivation + var irrResultDeriv = function (values, dates, rate) { + var r = rate + 1; + var result = 0; + for (var i = 1; i < values.length; i++) { + var frac = moment(dates[i]).diff(moment(dates[0]), 'days') / 365; + result -= frac * values[i] / Math.pow(r, frac + 1); + } + return result; + }; + + // Check that values contains at least one positive value and one negative value + var positive = false; + var negative = false; + for (var i = 0; i < values.length; i++) { + if (values[i] > 0) { + positive = true; + } + if (values[i] < 0) { + negative = true; + } + } + + // Return error if values does not contain at least one positive value and one negative value + if (!positive || !negative) { + return '#NUM!'; + } + + // Initialize guess and resultRate + guess = guess || 0.1; + var resultRate = guess; + + // Set maximum epsilon for end of iteration + var epsMax = 1e-10; + + // Set maximum number of iterations + var iterMax = 50; + + // Implement Newton's method + var newRate, epsRate, resultValue; + var iteration = 0; + var contLoop = true; + do { + resultValue = irrResult(values, dates, resultRate); + newRate = resultRate - resultValue / irrResultDeriv(values, dates, resultRate); + epsRate = Math.abs(newRate - resultRate); + resultRate = newRate; + contLoop = (epsRate > epsMax) && (Math.abs(resultValue) > epsMax); + } while (contLoop && (++iteration < iterMax)); + + if (contLoop) { + return '#NUM!'; + } + + // Return internal rate of return + return resultRate; + }; + + Formula.XNPV = function (rate, values, dates) { + var result = 0; + for (var i = 0; i < values.length; i++) { + result += values[i] / Math.pow(1 + rate, moment(dates[i]).diff(moment(dates[0]), 'days') / 365); + } + return result; + }; + + Formula.YIELD = function () { + return; + }; + + Formula.YIELDDISC = function () { + return; + }; + + Formula.YIELDMAT = function () { + }; + + + // Information functions + + Formula.ISNUMBER = function (number) { + return (!isNaN(parseFloat(number)) && isFinite(number)) ? true : false; + }; + + + // Logical functions + + Formula.AND = function () { + var result = true; + for (var i = 0; i < arguments.length; i++) { + if (!arguments[i]) { + result = false; + } + } + return result; + }; + + Formula.FALSE = function () { + return false; + }; + + Formula.SWITCH = function () { + var result; + if (arguments.length > 0) { + var targetValue = arguments[0]; + var argc = arguments.length - 1; + var switchCount = Math.floor(argc / 2); + var switchSatisfied = false; + var defaultClause = argc % 2 === 0 ? null : arguments[arguments.length - 1]; + + if (switchCount) { + for (var index = 0; index < switchCount; index++) { + if (targetValue === arguments[index * 2 + 1]) { + result = arguments[index * 2 + 2]; + switchSatisfied = true; + break; + } + } + } + + if (!switchSatisfied && defaultClause) { + result = defaultClause; + } + } + + return result; + }; + + Formula.IF = function (test, then_value, otherwise_value) { + return test?then_value:otherwise_value; + }; + + Formula.IFNA = function (value, value_if_na) { + return (value === '#N/A') ? value_if_na : value; + }; + + Formula.NOT = function (logical) { + return !logical; + }; + + Formula.OR = function () { + var result = false; + for (var i = 0; i < arguments.length; i++) { + if (arguments[i]) { + result = true; + } + } + return result; + }; + + Formula.TRUE = function () { + return true; + }; + + Formula.XOR = function () { + var result = 0; + for (var i = 0; i < arguments.length; i++) { + if (arguments[i]) { + result++; + } + } + return (Math.floor(Math.abs(result)) & 1) ? true : false; + }; + + + // Lookup and reference functions + + Formula.REFERENCE = function (context, reference) { + try { + var path = reference.split('.'), + result = context; + _(path).forEach(function (step) { + if (step[step.length - 1] === ']') { + var opening = step.indexOf('['); + var index = step.substring(opening + 1, step.length - 1); + result = result[step.substring(0, opening)][index]; + } else { + result = result[step]; + } + }); + return result; + } catch (error) { + return; + } + }; + + + // Math functions + + Formula.ABS = function (number) { + return Math.abs(number); + }; + + Formula.ACOS = function (number) { + return Math.acos(number); + }; + + Formula.ACOSH = function (number) { + return Math.log(number + Math.sqrt(number * number - 1)); + }; + + Formula.ACOT = function (number) { + return Math.atan(1 / number); + }; + + Formula.ACOTH = function (number) { + return 0.5 * Math.log((number + 1) / (number - 1)); + }; + + Formula.AGGREGATE = function (function_code) { + var result = []; + for (var i = 2; i < arguments.length; i++) { + switch (function_code) { + case 1: + result[i - 2] = Formula.AVERAGE(arguments[i]); + break; + case 2: + result[i - 2] = Formula.COUNT(arguments[i]); + break; + case 3: + result[i - 2] = Formula.COUNTA(arguments[i]); + break; + case 4: + result[i - 2] = Formula.MAX(arguments[i]); + break; + case 5: + result[i - 2] = Formula.MIN(arguments[i]); + break; + case 6: + result[i - 2] = Formula.PRODUCT(arguments[i]); + break; + case 7: + result[i - 2] = Formula.STDEVS(arguments[i]); + break; + case 8: + result[i - 2] = Formula.STDEVP(arguments[i]); + break; + case 9: + result[i - 2] = Formula.SUM(arguments[i]); + break; + case 10: + result[i - 2] = Formula.VARS(arguments[i]); + break; + case 11: + result[i - 2] = Formula.VARP(arguments[i]); + break; + case 12: + result[i - 2] = Formula.MEDIAN(arguments[i]); + break; + case 13: + result[i - 2] = Formula.MODESNGL(arguments[i]); + break; + case 14: + result[i - 2] = Formula.LARGE(arguments[i]); + break; + case 15: + result[i - 2] = Formula.SMALL(arguments[i]); + break; + case 16: + result[i - 2] = Formula.PERCENTILEINC(arguments[i]); + break; + case 17: + result[i - 2] = Formula.QUARTILEINC(arguments[i]); + break; + case 18: + result[i - 2] = Formula.PERCENTILEEXC(arguments[i]); + break; + case 19: + result[i - 2] = Formula.QUARTILEEXC(arguments[i]); + break; + } + } + return result; + }; + + Formula.ARABIC = function (text) { + // Credits: Rafa? Kukawski + if (!/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/.test(text)) { + throw new Error('Incorrect roman number'); + } + var r = 0; + text.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, function (i) { + r += {M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1}[i]; + }); + return r; + }; + + Formula.ASIN = function (number) { + return Math.asin(number); + }; + + Formula.ASINH = function (number) { + return Math.log(number + Math.sqrt(number * number + 1)); + }; + + Formula.ATAN = function (number) { + return Math.atan(number); + }; + + Formula.ATAN2 = function (number_x, number_y) { + return Math.atan2(number_x, number_y); + }; + + Formula.ATANH = function (number) { + return Math.log((1 + number) / (1 - number)) / 2; + }; + + Formula.BASE = function (number, radix, min_length) { + min_length = (typeof min_length === 'undefined') ? 0 : min_length; + var result = number.toString(radix); + return new Array(Math.max(min_length + 1 - result.length, 0)).join('0') + result; + }; + + Formula.CEILING = function (number, significance, mode) { + if (significance === 0) { + return 0; + } + significance = (typeof significance === 'undefined') ? 1 : Math.abs(significance); + mode = (typeof mode === 'undefined') ? 0 : mode; + var precision = -Math.floor(Math.log(significance) / Math.log(10)); + if (number >= 0) { + return Formula.ROUND(Math.ceil(number / significance) * significance, precision); + } else { + if (mode === 0) { + return -Formula.ROUND(Math.floor(Math.abs(number) / significance) * significance, precision); + } else { + return -Formula.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision); + } + } + }; + + Formula.CEILINGMATH = Formula.CEILING; + + Formula.CEILINGPRECISE = Formula.CEILING; + + Formula.COMBIN = function (number, number_chosen) { + return Formula.FACT(number) / (Formula.FACT(number_chosen) * Formula.FACT(number - number_chosen)); + }; + + Formula.COMBINA = function (number, number_chosen) { + return (number === 0 && number_chosen === 0) ? 1 : Formula.COMBIN(number + number_chosen - 1, number - 1); + }; + + Formula.COS = Math.cos; + + Formula.COSH = function (number) { + return (Math.exp(number) + Math.exp(-number)) / 2; + }; + + Formula.COT = function (number) { + return 1 / Math.tan(number); + }; + + Formula.COTH = function (number) { + var e2 = Math.exp(2 * number); + return (e2 + 1) / (e2 - 1); + }; + + Formula.CSC = function (number) { + return 1 / Math.sin(number); + }; + + Formula.CSCH = function (number) { + return 2 / (Math.exp(number) - Math.exp(-number)); + }; + + Formula.DECIMAL = function (number, radix) { + return parseInt(number, radix); + }; + + Formula.DEGREES = function (number) { + return number * 180 / Math.PI; + }; + + Formula.EVEN = function (number) { + return Formula.CEILING(number, -2, -1); + }; + + Formula.EXP = Math.exp; + + Formula.FACT = function (number) { + var n = Math.floor(number); + if (n === 0 || n === 1) { + return 1; + } else if (MEMOIZED_FACT[n] > 0) { + return MEMOIZED_FACT[n]; + } else { + MEMOIZED_FACT[n] = Formula.FACT(n - 1) * n; + return MEMOIZED_FACT[n]; + } + }; + + Formula.FACTDOUBLE = function (number) { + var n = Math.floor(number); + if (n <= 0) { + return 1; + } else { + return n * Formula.FACTDOUBLE(n - 2); + } + }; + + Formula.FLOOR = function (number, significance, mode) { + if (significance === 0) { + return 0; + } + + significance = significance ? Math.abs(significance) : 1; + var precision = -Math.floor(Math.log(significance) / Math.log(10)); + if (number >= 0) { + return Formula.ROUND(Math.floor(number / significance) * significance, precision); + } else if (mode === 0 || typeof mode === 'undefined') { + return -Formula.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision); + } + return -Formula.ROUND(Math.floor(Math.abs(number) / significance) * significance, precision); + }; + + Formula.FLOORMATH = Formula.FLOOR; + + Formula.FLOORPRECISE = function(number, significance) { + if (significance === 0) { + return 0; + } + + significance = significance ? Math.abs(significance) : 1; + var precision = -Math.floor(Math.log(significance) / Math.log(10)); + if (number >= 0) { + return Formula.ROUND(Math.round(number / significance) * significance, precision); + } + return -Formula.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision); + }; + + Formula.GCD = function () { + // Credits: Andrew Pociu + for (var r, a, i = arguments.length - 1, result = arguments[i]; i;) { + for (a = arguments[--i]; (r = a % result); a = result, result = r) { + //empty + } + } + return result; + }; + + Formula.INT = function (number) { + return Math.floor(number); + }; + + Formula.ISEVEN = function (number) { + return (Math.floor(Math.abs(number)) & 1) ? false : true; + }; + + Formula.ISOCEILING = Formula.CEILING; + + Formula.ISODD = function (number) { + return (Math.floor(Math.abs(number)) & 1) ? true : false; + }; + + Formula.LCM = function () { + // Credits: Jonas Raoni Soares Silva + var o = Formula.ARGSTOARRAY(arguments); + for (var i, j, n, d, r = 1; (n = o.pop()) !== undefined;) { + while (n > 1) { + if (n % 2) { + for (i = 3, j = Math.floor(Math.sqrt(n)); i <= j && n % i; i += 2) { + //empty + } + d = (i <= j) ? i : n; + } else { + d = 2; + } + for (n /= d, r *= d, i = o.length; i; (o[--i] % d) === 0 && (o[i] /= d) === 1 && o.splice(i, 1)) { + //empty + } + } + } + return r; + }; + + Formula.LN = function (number) { + return Math.log(number); + }; + + Formula.LOG = function (number, base) { + base = (typeof base === 'undefined') ? 10 : base; + return Math.log(number) / Math.log(base); + }; + + Formula.LOG10 = function (number) { + return Math.log(number) / Math.log(10); + }; + + Formula.MDETERM = numeric.det; + + Formula.MINVERSE = numeric.inv; + + Formula.MMULT = numeric.dot; + + Formula.MOD = function (dividend, divisor) { + var modulus = Math.abs(dividend % divisor); + return (divisor > 0) ? modulus : -modulus; + }; + + Formula.MROUND = function (number, multiple) { + if (number * multiple < 0) { + throw new Error('Number and multiple must have the same sign.'); + } + + return Math.round(number / multiple) * multiple; + }; + + Formula.MULTINOMIAL = function () { + var sum = 0; + var divisor = 1; + for (var i = 0; i < arguments.length; i++) { + sum += arguments[i]; + divisor *= Formula.FACT(arguments[i]); + } + return Formula.FACT(sum) / divisor; + }; + + Formula.MUNIT = numeric.identity; + + Formula.ODD = function (number) { + var temp = Math.ceil(Math.abs(number)); + temp = (temp & 1) ? temp : temp + 1; + return (number > 0) ? temp : -temp; + }; + + Formula.E = function () { + return Math.E; + }; + + Formula.PI = function () { + return Math.PI; + }; + + Formula.POWER = function (number, power) { + var result = Math.pow(number, power); + if (isNaN(result)) { + return '#NUM!'; + } + + return result; + }; + + Formula.PRODUCT = function () { + var result = 1; + for (var i = 0; i < arguments.length; i++) { + result *= arguments[i]; + } + return result; + }; + + Formula.QUOTIENT = function (numerator, denominator) { + return (numerator / denominator).toFixed(0); + }; + + Formula.RADIANS = function (number) { + return number * Math.PI / 180; + }; + + Formula.RAND = function () { + return Math.random(); + }; + + Formula.RANDBETWEEN = function (bottom, top) { + // Creative Commons Attribution 3.0 License + // Copyright (c) 2012 eqcode + return bottom + Math.ceil((top - bottom + 1) * Math.random()) - 1; + }; + + Formula.ROUND = function (number, digits) { + return Math.round(number * Math.pow(10, digits)) / Math.pow(10, digits); + }; + + Formula.ROUNDDOWN = function (number, digits) { + var sign = (number > 0) ? 1 : -1; + return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); + }; + + Formula.ROUNDUP = function (number, digits) { + var sign = (number > 0) ? 1 : -1; + return sign * (Math.ceil(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); + }; + + Formula.SERIESSUM = function (x, n, m, coefficients) { + var result = coefficients[0] * Math.pow(x, n); + for (var i = 1; i < coefficients.length; i++) { + result += coefficients[i] * Math.pow(x, n + i * m); + } + return result; + }; + + Formula.SEC = function (number) { + return 1 / Math.cos(number); + }; + + Formula.SECH = function (number) { + return 2 / (Math.exp(number) + Math.exp(-number)); + }; + + Formula.SIGN = function (number) { + if (number < 0) { + return -1; + } else if (number === 0) { + return 0; + } else { + return 1; + } + }; + + Formula.SIN = Math.sin; + + Formula.SINH = function (number) { + return (Math.exp(number) - Math.exp(-number)) / 2; + }; + + Formula.SQRT = Math.sqrt; + + Formula.SQRTPI = function (number) { + return Math.sqrt(number * Math.PI); + }; + + Formula.SUBTOTAL = function (function_code) { + var result = []; + for (var i = 1; i < arguments.length; i++) { + switch (function_code) { + case 1: + result[i - 1] = Formula.AVERAGE(arguments[i]); + break; + case 2: + result[i - 1] = Formula.COUNT(arguments[i]); + break; + case 3: + result[i - 1] = Formula.COUNTA(arguments[i]); + break; + case 4: + result[i - 1] = Formula.MAX(arguments[i]); + break; + case 5: + result[i - 1] = Formula.MIN(arguments[i]); + break; + case 6: + result[i - 1] = Formula.PRODUCT(arguments[i]); + break; + case 7: + result[i - 1] = Formula.STDEV(arguments[i]); + break; + case 8: + result[i - 1] = Formula.STDEVP(arguments[i]); + break; + case 9: + result[i - 1] = Formula.SUM(arguments[i]); + break; + case 10: + result[i - 1] = Formula.VAR(arguments[i]); + break; + case 11: + result[i - 1] = Formula.VARP(arguments[i]); + break; + } + } + return result; + }; + + Formula.SUM = function () { + var numbers = Formula.FLATTEN(arguments); + var result = 0; + for (var i = 0; i < numbers.length; i++) { + if (numbers[i] instanceof Array) { + for (var j = 0; j < numbers[i].length; j++) { + result += (Formula.ISNUMBER(numbers[i][j])) ? numbers[i][j] : 0; + } + } else { + result += (Formula.ISNUMBER(numbers[i])) ? numbers[i] : 0; + } + } + + return result; + }; + + Formula.SUMIF = function (range, criteria) { + range = Formula.FLATTEN(range); + var result = 0; + for (var i = 0; i < range.length; i++) { + result += (eval(range[i] + criteria)) ? range[i] : 0; + } + return result; + }; + + Formula.SUMIFS = function () { + var criteria = (arguments.length - 1) / 2; + var range = arguments[0]; + var result = 0; + for (var i = 0; i < range.length; i++) { + var fit = true; + for (var j = 0; j < criteria; j++) { + if (!eval(arguments[2 * j + 1][i] + arguments[2 * j + 2])) { + fit = false; + } + } + result += (fit) ? range[i] : 0; + } + return result; + +// var args = Formula.ARGSTOARRAY(arguments); +// var range = Formula.FLATTEN(args.shift()); +// var criteria = args; +// +// var n_range_elements = range.length; +// var n_criterias = criteria.length; +// +// var result = 0; +// for (var i = 0; i < n_range_elements; i++) { +// var el = range[i]; +// var condition = ''; +// for (var c = 0; c < n_criterias; c++) { +// condition += el+criteria[c]; +// if (c !== n_criterias - 1) { +// condition += '&&'; +// } +// } +// if (eval(condition)) { +// result += el; +// } +// } +// return result; + }; + + Formula.SUMPRODUCT = function () { + var arrays = arguments.length + 1; + var result = 0; + for (var i = 0; i < arguments[0].length; i++) { + for (var j = 0; j < arguments[0][i].length; j++) { + var product = 1; + for (var k = 1; k < arrays; k++) { + product *= arguments[k - 1][i][j]; + } + result += product; + } + } + return result; + }; + + Formula.SUMSQ = function () { + var numbers = Formula.FLATTEN(arguments); + var result = 0; + for (var i = 0; i < numbers.length; i++) { + result += (Formula.ISNUMBER(numbers[i])) ? numbers[i] * numbers[i] : 0; + } + return result; + }; + + Formula.SUMX2MY2 = function (array_x, array_y) { + var result = 0; + array_x = Formula.FLATTEN(array_x); + array_y = Formula.FLATTEN(array_y); + for (var i = 0; i < array_x.length; i++) { + result += array_x[i] * array_x[i] - array_y[i] * array_y[i]; + } + return result; + }; + + Formula.SUMX2PY2 = function (array_x, array_y) { + var result = 0; + array_x = Formula.FLATTEN(array_x); + array_y = Formula.FLATTEN(array_y); + for (var i = 0; i < array_x.length; i++) { + result += array_x[i] * array_x[i] + array_y[i] * array_y[i]; + } + return result; + }; + + Formula.SUMXMY2 = function (array_x, array_y) { + var result = 0; + array_x = Formula.FLATTEN(array_x); + array_y = Formula.FLATTEN(array_y); + for (var i = 0; i < array_x.length; i++) { + result += Math.pow(array_x[i] - array_y[i], 2); + } + return result; + }; + + Formula.TAN = function (number) { + return Math.tan(number); + }; + + Formula.TANH = function (number) { + var e2 = Math.exp(2 * number); + return (e2 - 1) / (e2 + 1); + }; + + Formula.TRUNC = function (number, digits) { + digits = (typeof digits === 'undefined') ? 0 : digits; + var sign = (number > 0) ? 1 : -1; + return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); + }; + + + // Statistical functions + Formula.AVEDEV = function () { + var range = Formula.FLATTEN(arguments); + return jStat.sum(jStat(range).subtract(jStat.mean(range)).abs()[0]) / range.length; + }; + + Formula.AVERAGE = function () { + var range = Formula.NUMBERS(Formula.FLATTEN(arguments)); + var n = range.length; + var sum = 0; + var count = 0; + for (var i = 0; i < n; i++) { + sum += range[i]; + count += 1; + } + return sum / count; + }; + + Formula.AVERAGEA = function () { + var range = Formula.FLATTEN(arguments); + var n = range.length; + var sum = 0; + var count = 0; + for (var i = 0; i < n; i++) { + var el = range[i]; + if (typeof el === 'number') { + sum += el; + } + if (el === true) { + sum++; + } + if (el !== null) { + count++; + } + } + return sum / count; + }; + + Formula.AVERAGEIF = function (range, criteria, average_range) { + average_range = average_range || range; + range = Formula.FLATTEN(range); + average_range = Formula.FLATTEN(average_range); + var average_count = 0; + var result = 0; + for (var i = 0; i < range.length; i++) { + if (eval(range[i] + criteria)) { + result += average_range[i]; + average_count++; + } + } + return result / average_count; + }; + + Formula.AVERAGEIFS = function () { + // Does not work with multi dimensional ranges yet! + //http://office.microsoft.com/en-001/excel-help/averageifs-function-HA010047493.aspx + var args = Formula.ARGSTOARRAY(arguments); + var criteria = (args.length - 1) / 2; + var range = Formula.FLATTEN(args[0]); + var count = 0; + var result = 0; + for (var i = 0; i < range.length; i++) { + var condition = ''; + for (var j = 0; j < criteria; j++) { + condition += args[2 * j + 1][i] + args[2 * j + 2]; + if (j !== criteria - 1) { + condition += '&&'; + } + } + if (eval(condition)) { + result += range[i]; + count++; + } + } + + var average = result / count; + if (isNaN(average)) { + return 0; + } else { + return average; + } + }; + + Formula.BETADIST = function (x, alpha, beta, cumulative, A, B) { + A = (typeof A === 'undefined') ? 0 : A; + B = (typeof B === 'undefined') ? 1 : B; + x = (x - A) / (B - A); + return (cumulative) ? jStat.beta.cdf(x, alpha, beta) : jStat.beta.pdf(x, alpha, beta); + }; + + Formula.BETAINV = function (probability, alpha, beta, A, B) { + A = (typeof A === 'undefined') ? 0 : A; + B = (typeof B === 'undefined') ? 1 : B; + return jStat.beta.inv(probability, alpha, beta) * (B - A) + A; + }; + + Formula.BINOMDIST = function (successes, trials, probability, cumulative) { + return (cumulative) ? jStat.binomial.cdf(successes, trials, probability) : jStat.binomial.pdf(successes, trials, probability); + }; + + Formula.BINOMDISTRANGE = function (trials, probability, successes, successes2) { + successes2 = (typeof successes2 === 'undefined') ? successes : successes2; + var result = 0; + for (var i = successes; i <= successes2; i++) { + result += Formula.COMBIN(trials, i) * Math.pow(probability, i) * Math.pow(1 - probability, trials - i); + } + return result; + }; + + Formula.BINOMINV = function (trials, probability, alpha) { + var x = 0; + while (x <= trials) { + if (jStat.binomial.cdf(x, trials, probability) >= alpha) { + return x; + } + x++; + } + }; + + Formula.CHISQDIST = function (x, k, cumulative) { + return (cumulative) ? jStat.chisquare.cdf(x, k) : jStat.chisquare.pdf(x, k); + }; + + Formula.CHISQDISTRT = function () { + return; + }; + + Formula.CHISQINV = function (probability, k) { + return jStat.chisquare.inv(probability, k); + }; + + Formula.CHISQINVRT = function () { + return; + }; + + Formula.CHISQTEST = function () { + return; + }; + + Formula.CONFIDENCENORM = function (alpha, sd, n) { + return jStat.normalci(1, alpha, sd, n)[1] - 1; + }; + + Formula.CONFIDENCET = function (alpha, sd, n) { + return jStat.tci(1, alpha, sd, n)[1] - 1; + }; + + Formula.CORREL = function () { + return jStat.corrcoeff.apply(this, arguments); + }; + + Formula.COUNT = function () { + var numbers = Formula.NUMBERS(Formula.FLATTEN(arguments)); + return numbers.length; + }; + + Formula.COUNTA = function () { + var range = Formula.FLATTEN(arguments); + return range.length - Formula.COUNTBLANK(range); + }; + + Formula.COUNTBLANK = function () { + var range = Formula.FLATTEN(arguments); + var blanks = 0; + var element; + for (var i = 0; i < range.length; i++) { + element = range[i]; + if (element === null || element === '' || !element) { + blanks++; + } + } + return blanks; + }; + + Formula.COUNTIF = function (range, criteria) { + range = Formula.FLATTEN(range); + var matches = 0; + for (var i = 0; i < range.length; i++) { + if (range[i].match(new RegExp(criteria))) { + matches++; + } + } + return matches; +// if (!/[<>=!]/.test(criteria)) { +// criteria = '=="'+criteria+'"'; +// } +// var matches = 0; +// for (var i = 0; i < range.length; i++) { +// if (typeof range[i] !== 'string') { +// if (eval(range[i]+criteria)) { +// matches++; +// } +// } else { +// if (eval('"'+range[i]+'"'+criteria)) { +// matches++; +// } +// } +// } +// return matches; + }; + + Formula.COUNTIFS = function () { + var criteria = (arguments.length - 1) / 2; + var range = arguments[0]; + var result = 0; + for (var i = 0; i < range.length; i++) { + var fit = true; + for (var j = 0; j < criteria; j++) { + if (!eval(arguments[2 * j + 1][i] + arguments[2 * j + 2])) { + fit = false; + } + } + result += (fit) ? 1 : 0; + } + return result; + +// var args = Formula.ARGSTOARRAY(arguments); +// var results = new Array(Formula.FLATTEN(args[0]).length); +// for (var i = 0; i < results.length; i++) { +// results[i] = true; +// } +// for (i = 0; i < args.length; i += 2) { +// var range = Formula.FLATTEN(args[i]); +// var criteria = args[i + 1]; +// if (!/[<>=!]/.test(criteria)) { +// criteria = '=="'+criteria+'"'; +// } +// for (var j = 0; j < range.length; j++) { +// if (typeof range[j] !== 'string') { +// results[j] = results[j] && eval(range[j]+criteria); +// } else { +// results[j] = results[j] && eval('"'+range[j]+'"'+criteria); +// } +// } +// } +// var result = 0; +// for (i = 0; i < results.length; i++) { +// if (results[i]) { +// result++; +// } +// } +// return result; + }; + + Formula.COUNTUNIQUE = function () { + return _.uniq(Formula.FLATTEN(arguments)).length; + }; + + Formula.COVARIANCEP = function (array1, array2) { + array1 = Formula.FLATTEN(array1); + array2 = Formula.FLATTEN(array2); + + var mean1 = jStat.mean(array1); + var mean2 = jStat.mean(array2); + var result = 0; + var n = array1.length; + for (var i = 0; i < n; i++) { + result += (array1[i] - mean1) * (array2[i] - mean2); + } + return result / n; + }; + + Formula.COVARIANCES = function () { + return jStat.covariance.apply(this, simplifyArguments(arguments)); + }; + + Formula.DEVSQ = function () { + var range = Formula.ARGSCONCAT(arguments); + var mean = jStat.mean(range); + var result = 0; + for (var i = 0; i < range.length; i++) { + result += Math.pow((range[i] - mean), 2); + } + return result; + }; + + Formula.EXPONDIST = function (x, lambda, cumulative) { + return (cumulative) ? jStat.exponential.cdf(x, lambda) : jStat.exponential.pdf(x, lambda); + }; + + Formula.FDIST = function (x, d1, d2, cumulative) { + return (cumulative) ? jStat.centralF.cdf(x, d1, d2) : jStat.centralF.pdf(x, d1, d2); + }; + + Formula.FDISTRT = function () { + return; + }; + + Formula.FINV = function (probability, d1, d2) { + if (probability <= 0.0 || probability > 1.0) { + return '#NUM!'; + } + + return jStat.centralF.inv(1.0 - probability, d1, d2); + }; + + Formula.FINVRT = function () { + return; + }; + + Formula.FTEST = function () { + return; + }; + + Formula.FISHER = function (x) { + return Math.log((1 + x) / (1 - x)) / 2; + }; + + Formula.FISHERINV = function (y) { + var e2y = Math.exp(2 * y); + return (e2y - 1) / (e2y + 1); + }; + + Formula.FORECAST = function (x, data_y, data_x) { + data_x = Formula.FLATTEN(data_x); + data_y = Formula.FLATTEN(data_y); + + var xmean = jStat.mean(data_x); + var ymean = jStat.mean(data_y); + var n = data_x.length; + var num = 0; + var den = 0; + for (var i = 0; i < n; i++) { + num += (data_x[i] - xmean) * (data_y[i] - ymean); + den += Math.pow(data_x[i] - xmean, 2); + } + var b = num / den; + var a = ymean - b * xmean; + return a + b * x; + }; + + Formula.FREQUENCY = function (data, bins) { + var n = data.length; + var b = bins.length; + var r = []; + for (var i = 0; i <= b; i++) { + r[i] = 0; + for (var j = 0; j < n; j++) { + if (i === 0) { + if (data[j] <= bins[0]) { + r[0] += 1; + } + } else if (i < b) { + if (data[j] > bins[i - 1] && data[j] <= bins[i]) { + r[i] += 1; + } + } else if (i === b) { + if (data[j] > bins[b - 1]) { + r[b] += 1; + } + } + } + } + return r; + }; + + Formula.GAMMA = function () { + return jStat.gammafn.apply(this, arguments); + }; + + //TODO + Formula.GAMMADIST = function (/* x, alpha, beta, cumulative */) { + /* + var shape = alpha; + var scale = 1 / beta; + return (cumulative) ? jStat.gamma.cdf(x, shape, scale) : jStat.gamma.pdf(x, shape, scale); + */ + return; + }; + + //TODO + Formula.GAMMAINV = function (/* probability, alpha, beta */) { + /* + var shape = alpha; + var scale = 1 / beta; + return jStat.gamma.inv(probability, shape, scale); + */ + return; + }; + + Formula.GAMMALN = function () { + return jStat.gammaln.apply(this, arguments); + }; + + //TODO + Formula.GAMMALNPRECISE = function () { + return; + }; + + Formula.GAUSS = function (z) { + return jStat.normal.cdf(z, 0, 1) - 0.5; + }; + + Formula.GEOMEAN = function () { + return jStat.geomean(Formula.ARGSCONCAT(arguments)); + }; + + Formula.GROWTH = function (known_y, known_x, new_x, use_const) { + // Credits: Ilmari Karonen + + // Default values for optional parameters: + var i; + if (typeof(known_x) === 'undefined') { + known_x = []; + for (i = 1; i <= known_y.length; i++) { + known_x.push(i); + } + } + if (typeof(new_x) === 'undefined') { + new_x = []; + for (i = 1; i <= known_y.length; i++) { + new_x.push(i); + } + } + if (typeof(use_const) === 'undefined') { + use_const = true; + } + + // Calculate sums over the data: + var n = known_y.length; + var avg_x = 0; + var avg_y = 0; + var avg_xy = 0; + var avg_xx = 0; + for (i = 0; i < n; i++) { + var x = known_x[i]; + var y = Math.log(known_y[i]); + avg_x += x; + avg_y += y; + avg_xy += x * y; + avg_xx += x * x; + } + avg_x /= n; + avg_y /= n; + avg_xy /= n; + avg_xx /= n; + + // Compute linear regression coefficients: + var beta; + var alpha; + if (use_const) { + beta = (avg_xy - avg_x * avg_y) / (avg_xx - avg_x * avg_x); + alpha = avg_y - beta * avg_x; + } else { + beta = avg_xy / avg_xx; + alpha = 0; + } + + // Compute and return result array: + var new_y = []; + for (i = 0; i < new_x.length; i++) { + new_y.push(Math.exp(alpha + beta * new_x[i])); + } + return new_y; + }; + + Formula.HARMEAN = function () { + var range = Formula.ARGSCONCAT(arguments); + var n = range.length; + var den = 0; + for (var i = 0; i < n; i++) { + den += 1 / range[i]; + } + return n / den; + }; + + Formula.HYPGEOMDIST = function (x, n, M, N, cumulative) { + function pdf(x, n, M, N) { + return Formula.COMBIN(M, x) * Formula.COMBIN(N - M, n - x) / Formula.COMBIN(N, n); + } + + function cdf(x, n, M, N) { + var result = 0; + for (var i = 0; i <= x; i++) { + result += pdf(i, n, M, N); + } + return result; + } + + return (cumulative) ? cdf(x, n, M, N) : pdf(x, n, M, N); + }; + + Formula.INTERCEPT = function (data_y, data_x) { + return Formula.FORECAST(0, data_y, data_x); + }; + + Formula.KURT = function () { + var range = Formula.ARGSCONCAT(arguments); + var mean = jStat.mean(range); + var n = range.length; + var sigma = 0; + for (var i = 0; i < n; i++) { + sigma += Math.pow(range[i] - mean, 4); + } + sigma = sigma / Math.pow(jStat.stdev(range, true), 4); + return ((n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3))) * sigma - 3 * (n - 1) * (n - 1) / ((n - 2) * (n - 3)); + }; + + Formula.LARGE = function (array, k) { + return array.sort(function (a, b) { + return b - a; + })[k - 1]; + }; + + Formula.LINEST = function (data_y, data_x) { + var xmean = jStat.mean(data_x); + var ymean = jStat.mean(data_y); + var n = data_x.length; + var num = 0; + var den = 0; + for (var i = 0; i < n; i++) { + num += (data_x[i] - xmean) * (data_y[i] - ymean); + den += Math.pow(data_x[i] - xmean, 2); + } + var m = num / den; + var b = ymean - m * xmean; + return [m, b]; + }; + + //TODO + Formula.LOGEST = function () { + return; + }; + + Formula.LOGNORMDIST = function (x, mean, sd, cumulative) { + return (cumulative) ? jStat.lognormal.cdf(x, mean, sd) : jStat.lognormal.pdf(x, mean, sd); + }; + + Formula.LOGNORMINV = function (probability, mean, sd) { + return jStat.lognormal.inv(probability, mean, sd); + }; + + Formula.MAX = function () { + var range = Formula.FLATTEN(arguments); + var n = range.length; + var max = (n > 0) ? range[0] : 0; + for (var i = 0; i < n; i++) { + max = (range[i] > max && (range[i] !== true) && (range[i] !== false)) ? range[i] : max; + } + return max; + }; + + Formula.MAXA = function () { + var range = Formula.FLATTEN(arguments); + return (range.length > 0) ? Math.max.apply(Math, range) : 0; + }; + + Formula.MEDIAN = function () { + return jStat.median(Formula.FLATTEN(arguments)); + }; + + Formula.MIN = function () { + var range = Formula.FLATTEN(arguments); + var n = range.length; + var min = (n > 0) ? range[0] : 0; + for (var i = 0; i < n; i++) { + min = (range[i] < min && (range[i] !== true) && (range[i] !== false)) ? range[i] : min; + } + return min; + }; + + Formula.MINA = function () { + var range = Formula.FLATTEN(arguments); + return (range.length > 0) ? Math.min.apply(Math, range) : 0; + }; + + Formula.MODEMULT = function () { + // Credits: Roönaän + var range = Formula.ARGSCONCAT(arguments), + n = range.length, + count = {}, + maxItems = [], + max = 0, + currentItem; + for (var i = 0; i < n; i++) { + currentItem = range[i]; + count[currentItem] = count[currentItem] ? count[currentItem] + 1 : 1; + if (count[currentItem] > max) { + max = count[currentItem]; + maxItems = []; + } + if (count[currentItem] === max) { + maxItems[maxItems.length] = currentItem; + } + } + return maxItems; + }; + + Formula.MODESNGL = function () { + return Formula.MODEMULT(Formula.ARGSCONCAT(arguments)).sort(function (a, b) { + return a - b; + })[0]; + }; + + Formula.NEGBINOMDIST = function (k, r, p, cumulative) { + return (cumulative) ? jStat.negbin.cdf(k, r, p) : jStat.negbin.pdf(k, r, p); + }; + + Formula.NORMDIST = function (x, mean, sd, cumulative) { + // Check parameters + if (isNaN(x) || isNaN(mean) || isNaN(sd)) { + return '#VALUE!'; + } + if (sd <= 0) { + return '#NUM!'; + } + + // Return normal distribution computed by jStat [http://jstat.org] + return (cumulative) ? jStat.normal.cdf(x, mean, sd) : jStat.normal.pdf(x, mean, sd); + }; + + Formula.NORMINV = function (probability, mean, sd) { + return jStat.normal.inv(probability, mean, sd); + }; + + Formula.NORMSDIST = function (z, cumulative) { + return (cumulative) ? jStat.normal.cdf(z, 0, 1) : jStat.normal.pdf(z, 0, 1); + }; + + Formula.NORMSINV = function (probability) { + return jStat.normal.inv(probability, 0, 1); + }; + + Formula.PEARSON = function (data_x, data_y) { + var xmean = jStat.mean(data_x); + var ymean = jStat.mean(data_y); + var n = data_x.length; + var num = 0; + var den1 = 0; + var den2 = 0; + for (var i = 0; i < n; i++) { + num += (data_x[i] - xmean) * (data_y[i] - ymean); + den1 += Math.pow(data_x[i] - xmean, 2); + den2 += Math.pow(data_y[i] - ymean, 2); + } + return num / Math.sqrt(den1 * den2); + }; + + Formula.PERCENTILEEXC = function (array, k) { + array = array.sort(function (a, b) { + { + return a - b; + } + }); + var n = array.length; + if (k < 1 / (n + 1) || k > 1 - 1 / (n + 1)) { + return '#NUM!'; + } + var l = k * (n + 1) - 1; + var fl = Math.floor(l); + return Formula.CLEANFLOAT((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl])); + }; + + Formula.PERCENTILEINC = function (array, k) { + array = array.sort(function (a, b) { + return a - b; + }); + var n = array.length; + var l = k * (n - 1); + var fl = Math.floor(l); + return Formula.CLEANFLOAT((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl])); + }; + + Formula.PERCENTRANKEXC = function (array, x, significance) { + array = array.sort(function (a, b) { + return a - b; + }); + var uniques = _.uniq(array); + var n = array.length; + var m = uniques.length; + significance = (typeof significance === 'undefined') ? 3 : significance; + var power = Math.pow(10, significance); + var result = 0; + var match = false; + var i = 0; + while (!match && i < m) { + if (x === uniques[i]) { + result = (array.indexOf(uniques[i]) + 1) / (n + 1); + match = true; + } else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) { + result = (array.indexOf(uniques[i]) + 1 + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n + 1); + match = true; + } + i++; + } + return Math.floor(result * power) / power; + }; + + Formula.PERCENTRANKINC = function (array, x, significance) { + array = array.sort(function (a, b) { + return a - b; + }); + var uniques = _.uniq(array); + var n = array.length; + var m = uniques.length; + significance = (typeof significance === 'undefined') ? 3 : significance; + var power = Math.pow(10, significance); + var result = 0; + var match = false; + var i = 0; + while (!match && i < m) { + if (x === uniques[i]) { + result = array.indexOf(uniques[i]) / (n - 1); + match = true; + } else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) { + result = (array.indexOf(uniques[i]) + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n - 1); + match = true; + } + i++; + } + return Math.floor(result * power) / power; + }; + + Formula.PERMUT = function (number, number_chosen) { + return Formula.FACT(number) / Formula.FACT(number - number_chosen); + }; + + Formula.PERMUTATIONA = function (number, number_chosen) { + return Math.pow(number, number_chosen); + }; + + Formula.PHI = function (x) { + return Math.exp(-0.5 * x * x) / SQRT2PI; + }; + + Formula.POISSONDIST = function (x, mean, cumulative) { + return (cumulative) ? jStat.poisson.cdf(x, mean) : jStat.poisson.pdf(x, mean); + }; + + Formula.PROB = function (range, probability, lower, upper) { + if (typeof lower === 'undefined') { + return 0; + } + + upper = (typeof upper === 'undefined') ? lower : upper; + if (lower === upper) { + return (range.indexOf(lower) >= 0) ? probability[range.indexOf(lower)] : 0; + } + + var sorted = range.sort(function (a, b) { + return a - b; + }); + var n = sorted.length; + var result = 0; + for (var i = 0; i < n; i++) { + if (sorted[i] >= lower && sorted[i] <= upper) { + result += probability[range.indexOf(sorted[i])]; + } + } + return result; + }; + + Formula.QUARTILEEXC = function (range, quart) { + switch (quart) { + case 1: + return Formula.PERCENTILEEXC(range, 0.25); + case 2: + return Formula.PERCENTILEEXC(range, 0.5); + case 3: + return Formula.PERCENTILEEXC(range, 0.75); + default: + return '#NUM!'; + } + }; + + Formula.QUARTILEINC = function (range, quart) { + switch (quart) { + case 1: + return Formula.PERCENTILEINC(range, 0.25); + case 2: + return Formula.PERCENTILEINC(range, 0.5); + case 3: + return Formula.PERCENTILEINC(range, 0.75); + default: + return '#NUM!'; + } + }; + + Formula.RANKAVG = function (number, range, order) { + order = (typeof order === 'undefined') ? false : order; + var sort = (order) ? function (a, b) { + return a - b; + } : function (a, b) { + return b - a; + }; + range = range.sort(sort); + var count = Formula.COUNTIN(range, number); + return (count > 1) ? (2 * range.indexOf(number) + count + 1) / 2 : range.indexOf(number) + 1; + }; + + Formula.RANKEQ = function (number, range, order) { + order = (typeof order === 'undefined') ? false : order; + var sort = (order) ? function (a, b) { + return a - b; + } : function (a, b) { + return b - a; + }; + range = range.sort(sort); + return range.indexOf(number) + 1; + }; + + Formula.RSQ = function (data_x, data_y) { + return Math.pow(Formula.PEARSON(data_x, data_y), 2); + }; + + Formula.SKEW = function () { + var range = Formula.ARGSCONCAT(arguments); + var mean = jStat.mean(range); + var n = range.length; + var sigma = 0; + for (var i = 0; i < n; i++) { + sigma += Math.pow(range[i] - mean, 3); + } + return n * sigma / ((n - 1) * (n - 2) * Math.pow(jStat.stdev(range, true), 3)); + }; + + Formula.SKEWP = function () { + var range = Formula.ARGSCONCAT(arguments); + var mean = jStat.mean(range); + var n = range.length; + var m2 = 0; + var m3 = 0; + for (var i = 0; i < n; i++) { + m3 += Math.pow(range[i] - mean, 3); + m2 += Math.pow(range[i] - mean, 2); + } + m3 = m3 / n; + m2 = m2 / n; + return m3 / Math.pow(m2, 3 / 2); + }; + + Formula.SLOPE = function (data_y, data_x) { + data_y = Formula.FLATTEN(data_y) + data_x = Formula.FLATTEN(data_x) + var xmean = jStat.mean(data_x); + var ymean = jStat.mean(data_y); + var n = data_x.length; + var num = 0; + var den = 0; + for (var i = 0; i < n; i++) { + num += (data_x[i] - xmean) * (data_y[i] - ymean); + den += Math.pow(data_x[i] - xmean, 2); + } + return num / den; + }; + + Formula.SMALL = function (array, k) { + return array.sort(function (a, b) { + return a - b; + })[k - 1]; + }; + + Formula.STANDARDIZE = function (x, mean, sd) { + return (x - mean) / sd; + }; + + Formula.STDEVA = function () { + var range = Formula.FLATTEN(arguments); + var n = range.length; + var sigma = 0; + var mean = jStat.mean(range); + for (var i = 0; i < n; i++) { + sigma += Math.pow(range[i] - mean, 2); + } + return Math.sqrt(sigma / (n - 1)); + }; + + Formula.STDEVP = function () { + var range = Formula.FLATTEN(arguments); + var n = range.length; + var sigma = 0; + var count = 0; + var mean = Formula.AVERAGE(range); + for (var i = 0; i < n; i++) { + if (range[i] !== true && range[i] !== false) { + sigma += Math.pow(range[i] - mean, 2); + count++; + } + } + return Math.sqrt(sigma / count); + }; + + Formula.STDEVPA = function () { + var range = Formula.ARGSCONCAT(arguments); + var n = range.length; + var sigma = 0; + var mean = jStat.mean(range); + for (var i = 0; i < n; i++) { + sigma += Math.pow(range[i] - mean, 2); + } + return Math.sqrt(sigma / n); + }; + + Formula.STDEVS = function () { + var range = Formula.FLATTEN(arguments); + var n = range.length; + var sigma = 0; + var count = 0; + var mean = Formula.AVERAGE(range); + for (var i = 0; i < n; i++) { + if (range[i] !== true && range[i] !== false) { + sigma += Math.pow(range[i] - mean, 2); + count++; + } + } + return Math.sqrt(sigma / (count - 1)); + }; + + Formula.STEYX = function (data_y, data_x) { + var xmean = jStat.mean(data_x); + var ymean = jStat.mean(data_y); + var n = data_x.length; + var lft = 0; + var num = 0; + var den = 0; + for (var i = 0; i < n; i++) { + lft += Math.pow(data_y[i] - ymean, 2); + num += (data_x[i] - xmean) * (data_y[i] - ymean); + den += Math.pow(data_x[i] - xmean, 2); + } + return Math.sqrt((lft - num * num / den) / (n - 2)); + }; + + Formula.TDIST = function (x, df, cumulative) { + return (cumulative) ? jStat.studentt.cdf(x, df) : jStat.studentt.pdf(x, df); + }; + + //TODO + Formula.TDIST2T = function () { + return; + }; + + //TODO + Formula.TDISTRT = function () { + return; + }; + + //TODO + Formula.TINV = function (probability, df) { + return jStat.studentt.inv(probability, df); + }; + + //TODO + Formula.TINV2T = function () { + return; + }; + + //TODO + Formula.TTEST = function () { + return; + }; + + //TODO + Formula.TREND = function () { + return; + }; + + Formula.TRIMMEAN = function (range, percent) { + range = Formula.FLATTEN(range); + var trim = Formula.FLOOR(range.length * percent, 2) / 2; + return jStat.mean(_.initial(_.rest(range.sort(function (a, b) { + return a - b; + }), trim), trim)); + }; + + Formula.VARA = function () { + var range = Formula.FLATTEN(arguments); + var n = range.length; + var sigma = 0; + var count = 0; + var mean = Formula.AVERAGEA(range); + for (var i = 0; i < n; i++) { + var el = range[i]; + if (typeof el === 'number') { + sigma += Math.pow(el - mean, 2); + } else if (el === true) { + sigma += Math.pow(1 - mean, 2); + } else { + sigma += Math.pow(0 - mean, 2); + } + + if (el !== null) { + count++; + } + } + return sigma / (count - 1); + }; + + Formula.VARP = function () { + var range = Formula.NUMBERS(Formula.FLATTEN(arguments)); + var n = range.length; + var sigma = 0; + var count = 0; + var mean = Formula.AVERAGE(range); + for (var i = 0; i < n; i++) { + sigma += Math.pow(range[i] - mean, 2); + count++; + } + return sigma / count; + }; + + Formula.VARPA = function () { + var range = Formula.FLATTEN(arguments); + var n = range.length; + var sigma = 0; + var count = 0; + var mean = Formula.AVERAGEA(range); + for (var i = 0; i < n; i++) { + var el = range[i]; + if (typeof el === 'number') { + sigma += Math.pow(el - mean, 2); + } else if (el === true) { + sigma += Math.pow(1 - mean, 2); + } else { + sigma += Math.pow(0 - mean, 2); + } + + if (el !== null) { + count++; + } + } + return sigma / count; + }; + + Formula.VARS = function () { + var range = Formula.FLATTEN(arguments); + var n = range.length; + var sigma = 0; + var count = 0; + var mean = Formula.AVERAGE(range); + for (var i = 0; i < n; i++) { + if (range[i] !== true && range[i] !== false) { + sigma += Math.pow(range[i] - mean, 2); + count++; + } + } + return sigma / (count - 1); + }; + + Formula.WEIBULLDIST = function (x, alpha, beta, cumulative) { + return (cumulative) ? 1 - Math.exp(-Math.pow(x / beta, alpha)) : Math.pow(x, alpha - 1) * Math.exp(-Math.pow(x / beta, alpha)) * alpha / Math.pow(beta, alpha); + }; + + Formula.ZTEST = function (range, x, sigma) { + var n = range.length; + var sd = (typeof sigma === 'undefined') ? Formula.STDEVS(range) : sigma; + return 1 - Formula.NORMSDIST((Formula.AVERAGE(range) - x) / (sd / Math.sqrt(n)), Formula.TRUE); + }; + + + // Text functions + + Formula.CHAR = function (number) { + return String.fromCharCode(number); + }; + + Formula.CLEAN = function (text) { + return text.replace(/[\0-\x1F]/g, ""); + }; + + Formula.CODE = function (text) { + return text.charCodeAt(0); + }; + + Formula.CONCATENATE = function () { + var string = ''; + for (var i = 0; i < arguments.length; i++) { + if (arguments[i] !== null && arguments[i] !== undefined) { + string += arguments[i]; + } + } + + return string; + }; + + Formula.DOLLAR = function (number, decimals) { + decimals = (typeof decimals === 'undefined') ? 2 : decimals; + var format = ''; + if (decimals <= 0) { + number = Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals); + format = '($0,0)'; + } else if (decimals > 0) { + format = '($0,0.' + new Array(decimals + 1).join('0') + ')'; + } + return numeral(number).format(format); + }; + + Formula.EXACT = function (text1, text2) { + return text1 === text2; + }; + + Formula.FIND = function (find_text, within_text, position) { + position = (typeof position === 'undefined') ? 0 : position; + return within_text ? within_text.indexOf(find_text, position - 1) + 1 : null; + }; + + Formula.FIXED = function (number, decimals, no_commas) { + decimals = (typeof decimals === 'undefined') ? 2 : decimals; + no_commas = (typeof no_commas === 'undefined') ? false : no_commas; + var format = no_commas ? '0' : '0,0'; + if (decimals <= 0) { + number = Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals); + } else if (decimals > 0) { + format += '.' + new Array(decimals + 1).join('0'); + } + return numeral(number).format(format); + }; + + Formula.HTML2TEXT = function (value) { + var result = ''; + + if (value) { + if (value instanceof Array) { + value.forEach(function (line) { + if (result !== '') { + result += '\n'; + } + result += (line.replace(/<(?:.|\n)*?>/gm, '')); + }); + } else { + result = value.replace(/<(?:.|\n)*?>/gm, ''); + } + } + + return result; + }; + + Formula.HUMANIZE = function (value) { + if (value instanceof Date) { + var dvalue = moment(value); + if (dvalue.hours() || dvalue.minutes() || dvalue.seconds()) { + return dvalue.format("dddd, MMMM Do YYYY, h:mm:ss"); + } else { + return dvalue.format("dddd, MMMM Do YYYY"); + } + } + + return value; + }; + + Formula.JOIN = function (array, separator) { + return array.join(separator); + }; + + Formula.LEFT = function (text, number) { + number = (typeof number === 'undefined') ? 1 : number; + return text ? text.substring(0, number) : null; + }; + + Formula.LEN = function (text) { + return text ? text.length : 0; + }; + + Formula.LOWER = function (text) { + return text ? text.toLowerCase() : text; + }; + + Formula.MID = function (text, start, number) { + return text.substring(start - 1, number); + }; + + Formula.NUMBERVALUE = function (text, decimal_separator, group_separator) { + decimal_separator = (typeof decimal_separator === 'undefined') ? '.' : decimal_separator; + group_separator = (typeof group_separator === 'undefined') ? ',' : group_separator; + return Number(text.replace(decimal_separator, '.').replace(group_separator, '')); + }; + + Formula.NUMBERS = function () { + var possibleNumbers = Formula.FLATTEN(arguments); + return possibleNumbers.filter(function (el) { + return typeof el === 'number'; + }); + }; + + Formula.PROPER = function (text) { + if (!text) { return; } + return text.replace(/\w\S*/g, function (txt) { + return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); + }); + }; + + Formula.REGEXEXTRACT = function (text, regular_expression) { + var match = text.match(new RegExp(regular_expression)); + return match ? (match[match.length > 1 ? match.length - 1 : 0]) : null; + }; + + Formula.REGEXMATCH = function (text, regular_expression, full) { + var match = text.match(new RegExp(regular_expression)); + return full ? match : !!match; + }; + + Formula.REGEXREPLACE = function (text, regular_expression, replacement) { + return text.replace(new RegExp(regular_expression), replacement); + }; + + Formula.REPLACE = function (text, position, length, new_text) { + return text.substr(0, position - 1) + new_text + text.substr(position - 1 + length); + }; + + Formula.REPT = function (text, number) { + return new Array(number + 1).join(text); + }; + + Formula.RIGHT = function (text, number) { + number = (typeof number === 'undefined') ? 1 : number; + return text ? text.substring(text.length - number) : null; + }; + + Formula.ROMAN = function (number) { + // The MIT License + // Copyright (c) 2008 Steven Levithan + var digits = String(number).split(''); + var key = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; + var roman = ''; + var i = 3; + while (i--) { + roman = (key[+digits.pop() + (i * 10)] || '') + roman; + } + return new Array(+digits.join('') + 1).join('M') + roman; + }; + + Formula.SEARCH = function (find_text, within_text, position) { + position = (typeof position === 'undefined') ? 0 : position; + return within_text.toLowerCase().indexOf(find_text.toLowerCase(), position - 1) + 1; + }; + + Formula.SPLIT = function (text, separator) { + return _s.words(text, separator); + }; + + Formula.SUBSTITUTE = function (text, old_text, new_text, occurrence) { + if (!text || !old_text || !new_text) { + return text; + } else if (typeof occurrence === 'undefined') { + return text.replace(new RegExp(old_text, 'g'), new_text); + } else { + var index = 0; + var i = 0; + while (text.indexOf(old_text, index) > 0) { + index = text.indexOf(old_text, index + 1); + i++; + if (i === occurrence) { + return text.substring(0, index) + new_text + text.substring(index + old_text.length); + } + } + } + }; + + Formula.T = function (value) { + return (typeof value === "string") ? value : null; + }; + + Formula.TEXT = function (value, format) { + if (!value) { + return ''; + } + + if (value instanceof Object) { + try { + return JSON.stringify(value); + } catch (err) { + // ignore + return ''; + } + } + + if (typeof value === 'string') { + if (!format) { return value; } + return (format.indexOf('0') >= 0) ? numeral(value).format(format) : moment(new Date(value)).format(format); + } + + if (value.toString && typeof value.toString === 'function') { + return value.toString(); + } + + return ''; + }; + + Formula.TRIM = function (text) { + return _s.clean(text); + }; + + Formula.UNICHAR = Formula.CHAR; + + Formula.UNICODE = Formula.CODE; + + Formula.UPPER = function (text) { + return text.toUpperCase(); + }; + + Formula.VALUE = function (text) { + return numeral().unformat(text); + }; + + // Hashing function + Formula.MD5 = function (data, key, raw) { + return md5(data, key, raw); + }; + + Formula.NUMERAL = function (number, format) { + return numeral(number).format(format); + }; + + // Excel Error Handling + Formula.ISERR = function (value) { + return (['#DIV/0!', '#NAME?', '#NUM!', '#NULL!', '#REF!', '#VALUE!'].indexOf(value) >= 0 ) ? true : false; + }; + + Formula.ISERROR = function (value) { + return Formula.ISERR(value) || value === '#N/A'; + }; + + Formula.IFERROR = function (value, valueIfError) { + if (Formula.ISERROR(value)) { + return valueIfError; + } + + return value; + }; + return Formula; + } +}).call(this); + diff --git a/vendor/assets/javascripts/handsontable.formula.js b/vendor/assets/javascripts/handsontable.formula.js new file mode 100644 index 000000000..5197e4f11 --- /dev/null +++ b/vendor/assets/javascripts/handsontable.formula.js @@ -0,0 +1,418 @@ +(function(Handsontable) { + 'use strict'; + + function HandsontableFormula() { + + var isFormula = function(value) { + if (value) { + if (value[0] === '=') { + return true; + } + } + + return false; + }; + + var formulaRenderer = function(instance, TD, row, col, prop, value, cellProperties) { + if (instance.formulasEnabled && isFormula(value)) { + // translate coordinates into cellId + var cellId = instance.plugin.utils.translateCellCoords({ + row: row, + col: col + }), + prevFormula = null, + formula = null, + needUpdate = false, + error, result; + + if (!cellId) { + return; + } + + // get cell data + var item = instance.plugin.matrix.getItem(cellId); + + if (item) { + + needUpdate = !! item.needUpdate; + + if (item.error) { + prevFormula = item.formula; + error = item.error; + + if (needUpdate) { + error = null; + } + } + } + + // check if typed formula or cell value should be recalculated + if ((value && value[0] === '=') || needUpdate) { + + formula = value.substr(1).toUpperCase(); + + if (!error || formula !== prevFormula) { + + var currentItem = item; + + if (!currentItem) { + + // define item to rulesJS matrix if not exists + item = { + id: cellId, + formula: formula + }; + + // add item to matrix + currentItem = instance.plugin.matrix.addItem(item); + } + + // parse formula + var newValue = instance.plugin.parse(formula, { + row: row, + col: col, + id: cellId + }); + + // check if update needed + needUpdate = (newValue.error === '#NEED_UPDATE'); + + // update item value and error + instance.plugin.matrix.updateItem(currentItem, { + formula: formula, + value: newValue.result, + error: newValue.error, + needUpdate: needUpdate + }); + + error = newValue.error; + result = newValue.result; + + // update cell value in hot + value = error || result; + } + } + + if (error) { + // clear cell value + if (!value) { + // reset error + error = null; + } else { + // show error + value = error; + } + } + } + + // apply changes + if (cellProperties.type === 'numeric') { + numericCell.renderer.apply(this, [instance, TD, row, col, prop, value, cellProperties]); + } else { + textCell.renderer.apply(this, [instance, TD, row, col, prop, value, cellProperties]); + } + }; + + var afterChange = function(changes, source) { + var instance = this; + + if (!instance.formulasEnabled) { + return; + } + + if (source === 'edit' || source === 'undo' || source === 'autofill') { + + var rerender = false; + + changes.forEach(function(item) { + + var row = item[0], + col = item[1], + prevValue = item[2], + value = item[3]; + + var cellId = instance.plugin.utils.translateCellCoords({ + row: row, + col: col + }); + + // if changed value, all references cells should be recalculated + if (value[0] !== '=' || prevValue !== value) { + instance.plugin.matrix.removeItem(cellId); + + // get referenced cells + var deps = instance.plugin.matrix.getDependencies(cellId); + + // update cells + deps.forEach(function(itemId) { + instance.plugin.matrix.updateItem(itemId, { + needUpdate: true + }); + }); + + rerender = true; + } + }); + + if (rerender) { + instance.render(); + } + } + }; + + var beforeAutofillInsidePopulate = function(index, direction, data, deltas, iterators, selected) { + var instance = this; + + var r = index.row, + c = index.col, + value = data[r][c], + delta = 0, + rlength = data.length, // rows + clength = data ? data[0].length : 0; //cols + + if (value[0] === '=') { // formula + + if (['down', 'up'].indexOf(direction) !== -1) { + delta = rlength * iterators.row; + } else if (['right', 'left'].indexOf(direction) !== -1) { + delta = clength * iterators.col; + } + + return { + value: instance.plugin.utils.updateFormula(value, direction, delta), + iterators: iterators + } + + } else { // other value + + // increment or decrement values for more than 2 selected cells + if (rlength >= 2 || clength >= 2) { + + var newValue = instance.plugin.helper.number(value), + ii, + start; + + if (instance.plugin.utils.isNumber(newValue)) { + + if (['down', 'up'].indexOf(direction) !== -1) { + + delta = deltas[0][c]; + + if (direction === 'down') { + newValue += (delta * rlength * iterators.row); + } else { + + ii = (selected.row - r) % rlength; + start = ii > 0 ? rlength - ii : 0; + + newValue = instance.plugin.helper.number(data[start][c]); + + newValue += (delta * rlength * iterators.row); + + // last element in array -> decrement iterator + // iterator cannot be less than 1 + if (iterators.row > 1 && (start + 1) === rlength) { + iterators.row--; + } + } + + } else if (['right', 'left'].indexOf(direction) !== -1) { + delta = deltas[r][0]; + + if (direction === 'right') { + newValue += (delta * clength * iterators.col); + } else { + + ii = (selected.col - c) % clength; + start = ii > 0 ? clength - ii : 0; + + newValue = instance.plugin.helper.number(data[r][start]); + + newValue += (delta * clength * (iterators.col || 1)); + + // last element in array -> decrement iterator + // iterator cannot be less than 1 + if (iterators.col > 1 && (start + 1) === clength) { + iterators.col--; + } + } + } + + return { + value: newValue, + iterators: iterators + } + } + } + + } + + return { + value: value, + iterators: iterators + }; + }; + + var afterCreateRow = function(row, amount, auto) { + if (auto) { + return; + } + + var instance = this; + + var selectedRow = instance.plugin.utils.isArray(instance.getSelected()) ? instance.getSelected()[0] : undefined; + + if (instance.plugin.utils.isUndefined(selectedRow)) { + return; + } + + var direction = (selectedRow >= row) ? 'before' : 'after', + items = instance.plugin.matrix.getRefItemsToRow(row), + counter = 1, + changes = []; + + items.forEach(function(id) { + var item = instance.plugin.matrix.getItem(id), + formula = instance.plugin.utils.changeFormula(item.formula, 1, { + row: row + }), // update formula if needed + newId = id; + + if (formula !== item.formula) { // formula updated + + // change row index and get new coordinates + if ((direction === 'before' && selectedRow <= item.row) || (direction === 'after' && selectedRow < item.row)) { + newId = instance.plugin.utils.changeRowIndex(id, counter); + } + + var cellCoords = instance.plugin.utils.cellCoords(newId); + + if (newId !== id) { + // remove current item from matrix + instance.plugin.matrix.removeItem(id); + } + + // set updated formula in new cell + changes.push([cellCoords.row, cellCoords.col, '=' + formula]); + } + }); + + if (items) { + instance.plugin.matrix.removeItemsBelowRow(row); + } + + if (changes) { + instance.setDataAtCell(changes); + } + }; + + var afterCreateCol = function(col) { + var instance = this; + + var selectedCol = instance.plugin.utils.isArray(instance.getSelected()) ? instance.getSelected()[1] : undefined; + + if (instance.plugin.utils.isUndefined(selectedCol)) { + return; + } + + var items = instance.plugin.matrix.getRefItemsToColumn(col), + counter = 1, + direction = (selectedCol >= col) ? 'before' : 'after', + changes = []; + + items.forEach(function(id) { + + var item = instance.plugin.matrix.getItem(id), + formula = instance.plugin.utils.changeFormula(item.formula, 1, { + col: col + }), // update formula if needed + newId = id; + + if (formula !== item.formula) { // formula updated + + // change col index and get new coordinates + if ((direction === 'before' && selectedCol <= item.col) || (direction === 'after' && selectedCol < item.col)) { + newId = instance.plugin.utils.changeColIndex(id, counter); + } + + var cellCoords = instance.plugin.utils.cellCoords(newId); + + if (newId !== id) { + // remove current item from matrix if id changed + instance.plugin.matrix.removeItem(id); + } + + // set updated formula in new cell + changes.push([cellCoords.row, cellCoords.col, '=' + formula]); + } + }); + + if (items) { + instance.plugin.matrix.removeItemsBelowCol(col); + } + + if (changes) { + instance.setDataAtCell(changes); + } + }; + + var formulaCell = { + renderer: formulaRenderer, + editor: Handsontable.editors.TextEditor, + dataType: 'formula' + }; + + var textCell = { + renderer: Handsontable.renderers.TextRenderer, + editor: Handsontable.editors.TextEditor + }; + + var numericCell = { + renderer: Handsontable.renderers.NumericRenderer, + editor: Handsontable.editors.NumericEditor + }; + + this.init = function() { + var instance = this; + instance.formulasEnabled = !! instance.getSettings().formulas; + + if (instance.formulasEnabled) { + + var custom = { + cellValue: instance.getDataAtCell + }; + + instance.plugin = new ruleJS(); + instance.plugin.init(); + instance.plugin.custom = custom; + + Handsontable.cellTypes['formula'] = formulaCell; + + Handsontable.TextCell.renderer = formulaRenderer; + Handsontable.NumericCell.renderer = formulaRenderer; + + instance.addHook('afterChange', afterChange); + instance.addHook('beforeAutofillInsidePopulate', beforeAutofillInsidePopulate); + + instance.addHook('afterCreateRow', afterCreateRow); + instance.addHook('afterCreateCol', afterCreateCol); + + } else { + instance.removeHook('afterChange', afterChange); + instance.removeHook('beforeAutofillInsidePopulate', beforeAutofillInsidePopulate); + + instance.removeHook('afterCreateRow', afterCreateRow); + instance.removeHook('afterCreateCol', afterCreateCol); + } + }; + } + + var htFormula = new HandsontableFormula(); + + Handsontable.hooks.add('beforeInit', htFormula.init); + + Handsontable.hooks.add('afterUpdateSettings', function() { + htFormula.init.call(this, 'afterUpdateSettings') + }); + +})(Handsontable); diff --git a/vendor/assets/javascripts/jstat.js b/vendor/assets/javascripts/jstat.js new file mode 100644 index 000000000..c69a17a18 --- /dev/null +++ b/vendor/assets/javascripts/jstat.js @@ -0,0 +1,3251 @@ +this.j$ = this.jStat = (function(Math, undefined) { + +// For quick reference. +var concat = Array.prototype.concat; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +// Calculate correction for IEEE error +// TODO: This calculation can be improved. +function calcRdx(n, m) { + var val = n > m ? n : m; + return Math.pow(10, + 17 - ~~(Math.log(((val > 0) ? val : -val)) * Math.LOG10E)); +} + + +var isArray = Array.isArray || function isArray(arg) { + return toString.call(arg) === '[object Array]'; +}; + + +function isFunction(arg) { + return toString.call(arg) === '[object Function]'; +} + + +function isNumber(arg) { + return typeof arg === 'number' && arg === arg; +} + + +// Converts the jStat matrix to vector. +function toVector(arr) { + return concat.apply([], arr); +} + + +// The one and only jStat constructor. +function jStat() { + return new jStat._init(arguments); +} + + +// TODO: Remove after all references in src files have been removed. +jStat.fn = jStat.prototype; + + +// By separating the initializer from the constructor it's easier to handle +// always returning a new instance whether "new" was used or not. +jStat._init = function _init(args) { + var i; + + // If first argument is an array, must be vector or matrix. + if (isArray(args[0])) { + // Check if matrix. + if (isArray(args[0][0])) { + // See if a mapping function was also passed. + if (isFunction(args[1])) + args[0] = jStat.map(args[0], args[1]); + // Iterate over each is faster than this.push.apply(this, args[0]. + for (i = 0; i < args[0].length; i++) + this[i] = args[0][i]; + this.length = args[0].length; + + // Otherwise must be a vector. + } else { + this[0] = isFunction(args[1]) ? jStat.map(args[0], args[1]) : args[0]; + this.length = 1; + } + + // If first argument is number, assume creation of sequence. + } else if (isNumber(args[0])) { + this[0] = jStat.seq.apply(null, args); + this.length = 1; + + // Handle case when jStat object is passed to jStat. + } else if (args[0] instanceof jStat) { + // Duplicate the object and pass it back. + return jStat(args[0].toArray()); + + // Unexpected argument value, return empty jStat object. + // TODO: This is strange behavior. Shouldn't this throw or some such to let + // the user know they had bad arguments? + } else { + this[0] = []; + this.length = 1; + } + + return this; +}; +jStat._init.prototype = jStat.prototype; +jStat._init.constructor = jStat; + + +// Utility functions. +// TODO: for internal use only? +jStat.utils = { + calcRdx: calcRdx, + isArray: isArray, + isFunction: isFunction, + isNumber: isNumber, + toVector: toVector +}; + + +// Easily extend the jStat object. +// TODO: is this seriously necessary? +jStat.extend = function extend(obj) { + var i, j; + + if (arguments.length === 1) { + for (j in obj) + jStat[j] = obj[j]; + return this; + } + + for (i = 1; i < arguments.length; i++) { + for (j in arguments[i]) + obj[j] = arguments[i][j]; + } + + return obj; +}; + + +// Returns the number of rows in the matrix. +jStat.rows = function rows(arr) { + return arr.length || 1; +}; + + +// Returns the number of columns in the matrix. +jStat.cols = function cols(arr) { + return arr[0].length || 1; +}; + + +// Returns the dimensions of the object { rows: i, cols: j } +jStat.dimensions = function dimensions(arr) { + return { + rows: jStat.rows(arr), + cols: jStat.cols(arr) + }; +}; + + +// Returns a specified row as a vector +jStat.row = function row(arr, index) { + return arr[index]; +}; + + +// Returns the specified column as a vector +jStat.col = function cols(arr, index) { + var column = new Array(arr.length); + for (var i = 0; i < arr.length; i++) + column[i] = [arr[i][index]]; + return column; +}; + + +// Returns the diagonal of the matrix +jStat.diag = function diag(arr) { + var nrow = jStat.rows(arr); + var res = new Array(nrow); + for (var row = 0; row < nrow; row++) + res[row] = [arr[row][row]]; + return res; +}; + + +// Returns the anti-diagonal of the matrix +jStat.antidiag = function antidiag(arr) { + var nrow = jStat.rows(arr) - 1; + var res = new Array(nrow); + for (var i = 0; nrow >= 0; nrow--, i++) + res[i] = [arr[i][nrow]]; + return res; +}; + +// Transpose a matrix or array. +jStat.transpose = function transpose(arr) { + var obj = []; + var objArr, rows, cols, j, i; + + // Make sure arr is in matrix format. + if (!isArray(arr[0])) + arr = [arr]; + + rows = arr.length; + cols = arr[0].length; + + for (i = 0; i < cols; i++) { + objArr = new Array(rows); + for (j = 0; j < rows; j++) + objArr[j] = arr[j][i]; + obj.push(objArr); + } + + // If obj is vector, return only single array. + return obj.length === 1 ? obj[0] : obj; +}; + + +// Map a function to an array or array of arrays. +// "toAlter" is an internal variable. +jStat.map = function map(arr, func, toAlter) { + var row, nrow, ncol, res, col; + + if (!isArray(arr[0])) + arr = [arr]; + + nrow = arr.length; + ncol = arr[0].length; + res = toAlter ? arr : new Array(nrow); + + for (row = 0; row < nrow; row++) { + // if the row doesn't exist, create it + if (!res[row]) + res[row] = new Array(ncol); + for (col = 0; col < ncol; col++) + res[row][col] = func(arr[row][col], row, col); + } + + return res.length === 1 ? res[0] : res; +}; + + +// Destructively alter an array. +jStat.alter = function alter(arr, func) { + return jStat.map(arr, func, true); +}; + + +// Generate a rows x cols matrix according to the supplied function. +jStat.create = function create(rows, cols, func) { + var res = new Array(rows); + var i, j; + + if (isFunction(cols)) { + func = cols; + cols = rows; + } + + for (i = 0; i < rows; i++) { + res[i] = new Array(cols); + for (j = 0; j < cols; j++) + res[i][j] = func(i, j); + } + + return res; +}; + + +function retZero() { return 0; } + + +// Generate a rows x cols matrix of zeros. +jStat.zeros = function zeros(rows, cols) { + if (!isNumber(cols)) + cols = rows; + return jStat.create(rows, cols, retZero); +}; + + +function retOne() { return 1; } + + +// Generate a rows x cols matrix of ones. +jStat.ones = function ones(rows, cols) { + if (!isNumber(cols)) + cols = rows; + return jStat.create(rows, cols, retOne); +}; + + +// Generate a rows x cols matrix of uniformly random numbers. +jStat.rand = function rand(rows, cols) { + if (!isNumber(cols)) + cols = rows; + return jStat.create(rows, cols, Math.random); +}; + + +function retIdent(i, j) { return i === j ? 1 : 0; } + + +// Generate an identity matrix of size row x cols. +jStat.identity = function identity(rows, cols) { + if (!isNumber(cols)) + cols = rows; + return jStat.create(rows, cols, retIdent); +}; + + +// Tests whether a matrix is symmetric +jStat.symmetric = function symmetric(arr) { + var issymmetric = true; + var size = arr.length; + var row, col; + + if (arr.length !== arr[0].length) + return false; + + for (row = 0; row < size; row++) { + for (col = 0; col < size; col++) + if (arr[col][row] !== arr[row][col]) + return false; + } + + return true; +}; + + +// Set all values to zero. +jStat.clear = function clear(arr) { + return jStat.alter(arr, retZero); +}; + + +// Generate sequence. +jStat.seq = function seq(min, max, length, func) { + if (!isFunction(func)) + func = false; + + var arr = []; + var hival = calcRdx(min, max); + var step = (max * hival - min * hival) / ((length - 1) * hival); + var current = min; + var cnt; + + // Current is assigned using a technique to compensate for IEEE error. + // TODO: Needs better implementation. + for (cnt = 0; + current <= max; + cnt++, current = (min * hival + step * hival * cnt) / hival) { + arr.push((func ? func(current, cnt) : current)); + } + + return arr; +}; + + +// TODO: Go over this entire implementation. Seems a tragic waste of resources +// doing all this work. Instead, and while ugly, use new Function() to generate +// a custom function for each static method. + +// Quick reference. +var jProto = jStat.prototype; + +// Default length. +jProto.length = 0; + +// For internal use only. +// TODO: Check if they're actually used, and if they are then rename them +// to _* +jProto.push = Array.prototype.push; +jProto.sort = Array.prototype.sort; +jProto.splice = Array.prototype.splice; +jProto.slice = Array.prototype.slice; + + +// Return a clean array. +jProto.toArray = function toArray() { + return this.length > 1 ? slice.call(this) : slice.call(this)[0]; +}; + + +// Map a function to a matrix or vector. +jProto.map = function map(func, toAlter) { + return jStat(jStat.map(this, func, toAlter)); +}; + + +// Destructively alter an array. +jProto.alter = function alter(func) { + jStat.alter(this, func); + return this; +}; + + +// Extend prototype with methods that have no argument. +(function(funcs) { + for (var i = 0; i < funcs.length; i++) (function(passfunc) { + jProto[passfunc] = function(func) { + var self = this, + results; + // Check for callback. + if (func) { + setTimeout(function() { + func.call(self, jProto[passfunc].call(self)); + }); + return this; + } + results = jStat[passfunc](this); + return isArray(results) ? jStat(results) : results; + }; + })(funcs[i]); +})('transpose clear symmetric rows cols dimensions diag antidiag'.split(' ')); + + +// Extend prototype with methods that have one argument. +(function(funcs) { + for (var i = 0; i < funcs.length; i++) (function(passfunc) { + jProto[passfunc] = function(index, func) { + var self = this; + // check for callback + if (func) { + setTimeout(function() { + func.call(self, jProto[passfunc].call(self, index)); + }); + return this; + } + return jStat(jStat[passfunc](this, index)); + }; + })(funcs[i]); +})('row col'.split(' ')); + + +// Extend prototype with simple shortcut methods. +(function(funcs) { + for (var i = 0; i < funcs.length; i++) (function(passfunc) { + jProto[passfunc] = new Function( + 'return jStat(jStat.' + passfunc + '.apply(null, arguments));'); + })(funcs[i]); +})('create zeros ones rand identity'.split(' ')); + + +// Exposing jStat. +return jStat; + +}(Math)); +(function(jStat, Math) { + +var isFunction = jStat.utils.isFunction; + +// Ascending functions for sort +function ascNum(a, b) { return a - b; } + +function clip(arg, min, max) { + return Math.max(min, Math.min(arg, max)); +} + + +// sum of an array +jStat.sum = function sum(arr) { + var sum = 0; + var i = arr.length; + var tmp; + while (--i >= 0) + sum += arr[i]; + return sum; +}; + + +// sum squared +jStat.sumsqrd = function sumsqrd(arr) { + var sum = 0; + var i = arr.length; + while (--i >= 0) + sum += arr[i] * arr[i]; + return sum; +}; + + +// sum of squared errors of prediction (SSE) +jStat.sumsqerr = function sumsqerr(arr) { + var mean = jStat.mean(arr); + var sum = 0; + var i = arr.length; + var tmp; + while (--i >= 0) { + tmp = arr[i] - mean; + sum += tmp * tmp; + } + return sum; +}; + + +// product of an array +jStat.product = function product(arr) { + var prod = 1; + var i = arr.length; + while (--i >= 0) + prod *= arr[i]; + return prod; +}; + + +// minimum value of an array +jStat.min = function min(arr) { + var low = arr[0]; + var i = 0; + while (++i < arr.length) + if (arr[i] < low) + low = arr[i]; + return low; +}; + + +// maximum value of an array +jStat.max = function max(arr) { + var high = arr[0]; + var i = 0; + while (++i < arr.length) + if (arr[i] > high) + high = arr[i]; + return high; +}; + + +// mean value of an array +jStat.mean = function mean(arr) { + return jStat.sum(arr) / arr.length; +}; + + +// mean squared error (MSE) +jStat.meansqerr = function meansqerr(arr) { + return jStat.sumsqerr(arr) / arr.length; +}; + + +// geometric mean of an array +jStat.geomean = function geomean(arr) { + return Math.pow(jStat.product(arr), 1 / arr.length); +}; + + +// median of an array +jStat.median = function median(arr) { + var arrlen = arr.length; + var _arr = arr.slice().sort(ascNum); + // check if array is even or odd, then return the appropriate + return !(arrlen & 1) + ? (_arr[(arrlen / 2) - 1 ] + _arr[(arrlen / 2)]) / 2 + : _arr[(arrlen / 2) | 0 ]; +}; + + +// cumulative sum of an array +jStat.cumsum = function cumsum(arr) { + var len = arr.length; + var sums = new Array(len); + var i; + sums[0] = arr[0]; + for (i = 1; i < len; i++) + sums[i] = sums[i - 1] + arr[i]; + return sums; +}; + + +// successive differences of a sequence +jStat.diff = function diff(arr) { + var diffs = []; + var arrLen = arr.length; + var i; + for (i = 1; i < arrLen; i++) + diffs.push(arr[i] - arr[i - 1]); + return diffs; +}; + + +// mode of an array +// if there are multiple modes of an array, return all of them +// is this the appropriate way of handling it? +jStat.mode = function mode(arr) { + var arrLen = arr.length; + var _arr = arr.slice().sort(ascNum); + var count = 1; + var maxCount = 0; + var numMaxCount = 0; + var mode_arr = []; + var i; + + for (i = 0; i < arrLen; i++) { + if (_arr[i] === _arr[i + 1]) { + count++; + } else { + if (count > maxCount) { + mode_arr = [_arr[i]]; + maxCount = count; + numMaxCount = 0; + } + // are there multiple max counts + else if (count === maxCount) { + mode_arr.push(_arr[i]); + numMaxCount++; + } + // resetting count for new value in array + count = 1; + } + } + + return numMaxCount === 0 ? mode_arr[0] : mode_arr; +}; + + +// range of an array +jStat.range = function range(arr) { + return jStat.max(arr) - jStat.min(arr); +}; + +// variance of an array +// flag indicates population vs sample +jStat.variance = function variance(arr, flag) { + return jStat.sumsqerr(arr) / (arr.length - (flag ? 1 : 0)); +}; + + +// standard deviation of an array +// flag indicates population vs sample +jStat.stdev = function stdev(arr, flag) { + return Math.sqrt(jStat.variance(arr, flag)); +}; + + +// mean deviation (mean absolute deviation) of an array +jStat.meandev = function meandev(arr) { + var devSum = 0; + var mean = jStat.mean(arr); + var i; + for (i = arr.length - 1; i >= 0; i--) + devSum += Math.abs(arr[i] - mean); + return devSum / arr.length; +}; + + +// median deviation (median absolute deviation) of an array +jStat.meddev = function meddev(arr) { + var devSum = 0; + var median = jStat.median(arr); + var i; + for (i = arr.length - 1; i >= 0; i--) + devSum += Math.abs(arr[i] - median); + return devSum / arr.length; +}; + + +// coefficient of variation +jStat.coeffvar = function coeffvar(arr) { + return jStat.stdev(arr) / jStat.mean(arr); +}; + + +// quartiles of an array +jStat.quartiles = function quartiles(arr) { + var arrlen = arr.length; + var _arr = arr.slice().sort(ascNum); + return [ + _arr[ Math.round((arrlen) / 4) - 1 ], + _arr[ Math.round((arrlen) / 2) - 1 ], + _arr[ Math.round((arrlen) * 3 / 4) - 1 ] + ]; +}; + + +// Arbitary quantiles of an array. Direct port of the scipy.stats +// implementation by Pierre GF Gerard-Marchant. +jStat.quantiles = function quantiles(arr, quantilesArray, alphap, betap) { + var sortedArray = arr.slice().sort(ascNum); + var quantileVals = [quantilesArray.length]; + var n = arr.length; + var i, p, m, aleph, k, gamma; + + if (typeof alphap === 'undefined') + alphap = 3 / 8; + if (typeof betap === 'undefined') + betap = 3 / 8; + + for (i = 0; i < quantilesArray.length; i++) { + p = quantilesArray[i]; + m = alphap + p * (1 - alphap - betap); + aleph = n * p + m; + k = Math.floor(clip(aleph, 1, n - 1)); + gamma = clip(aleph - k, 0, 1); + quantileVals[i] = (1 - gamma) * sortedArray[k - 1] + gamma * sortedArray[k]; + } + + return quantileVals; +}; + +// The percentile rank of score in a given array. Returns the percentage +// of all values in the input array that are less than (kind='strict') or +// less or equal than (kind='weak') score. Default is weak. +jStat.percentileOfScore = function percentileOfScore(arr, score, kind) { + var counter = 0; + var len = arr.length; + var strict = false; + var value, i; + + if (kind === 'strict') + strict = true; + + for (i = 0; i < len; i++) { + value = arr[i]; + if ((strict && value < score) || + (!strict && value <= score)) { + counter++; + } + } + + return counter / len; +}; + +// covariance of two arrays +jStat.covariance = function covariance(arr1, arr2) { + var u = jStat.mean(arr1); + var v = jStat.mean(arr2); + var arr1Len = arr1.length; + var sq_dev = new Array(arr1Len); + var i; + + for (i = 0; i < arr1Len; i++) + sq_dev[i] = (arr1[i] - u) * (arr2[i] - v); + + return jStat.sum(sq_dev) / (arr1Len - 1); +}; + + +// (pearson's) population correlation coefficient, rho +jStat.corrcoeff = function corrcoeff(arr1, arr2) { + return jStat.covariance(arr1, arr2) / + jStat.stdev(arr1, 1) / + jStat.stdev(arr2, 1); +}; + + +var jProto = jStat.prototype; + + +// Extend jProto with method for calculating cumulative sums, as it does not +// run again in case of true. +// If a matrix is passed, automatically assume operation should be done on the +// columns. +jProto.cumsum = function(fullbool, func) { + var arr = []; + var i = 0; + var tmpthis = this; + + // Assignment reassignation depending on how parameters were passed in. + if (isFunction(fullbool)) { + func = fullbool; + fullbool = false; + } + + // Check if a callback was passed with the function. + if (func) { + setTimeout(function() { + func.call(tmpthis, jProto.cumsum.call(tmpthis, fullbool)); + }); + return this; + } + + // Check if matrix and run calculations. + if (this.length > 1) { + tmpthis = fullbool === true ? this : this.transpose(); + for (; i < tmpthis.length; i++) + arr[i] = jStat.cumsum(tmpthis[i]); + return arr; + } + + return jStat.cumsum(this[0], fullbool); +}; + + +// Extend jProto with methods which don't require arguments and work on columns. +(function(funcs) { + for (var i = 0; i < funcs.length; i++) (function(passfunc) { + // If a matrix is passed, automatically assume operation should be done on + // the columns. + jProto[passfunc] = function(fullbool, func) { + var arr = []; + var i = 0; + var tmpthis = this; + // Assignment reassignation depending on how parameters were passed in. + if (isFunction(fullbool)) { + func = fullbool; + fullbool = false; + } + // Check if a callback was passed with the function. + if (func) { + setTimeout(function() { + func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool)); + }); + return this; + } + // Check if matrix and run calculations. + if (this.length > 1) { + tmpthis = fullbool === true ? this : this.transpose(); + for (; i < tmpthis.length; i++) + arr[i] = jStat[passfunc](tmpthis[i]); + return fullbool === true + ? jStat[passfunc](jStat.utils.toVector(arr)) + : arr; + } + // Pass fullbool if only vector, not a matrix. for variance and stdev. + return jStat[passfunc](this[0], fullbool); + }; + })(funcs[i]); +})(('sum sumsqrd sumsqerr product min max mean meansqerr geomean median diff ' + + 'mode range variance stdev meandev meddev coeffvar quartiles').split(' ')); + + +// Extend jProto with functions that take arguments. Operations on matrices are +// done on columns. +(function(funcs) { + for (var i = 0; i < funcs.length; i++) (function(passfunc) { + jProto[passfunc] = function() { + var arr = []; + var i = 0; + var tmpthis = this; + var args = Array.prototype.slice.call(arguments); + + // If the last argument is a function, we assume it's a callback; we + // strip the callback out and call the function again. + if (isFunction(args[args.length - 1])) { + var callbackFunction = args[args.length - 1]; + var argsToPass = args.slice(0, args.length - 1); + + setTimeout(function() { + callbackFunction.call(tmpthis, + jProto[passfunc].apply(tmpthis, argsToPass)); + }); + return this; + + // Otherwise we curry the function args and call normally. + } else { + var callbackFunction = undefined; + var curriedFunction = function curriedFunction(vector) { + return jStat[passfunc].apply(tmpthis, [vector].concat(args)); + } + } + + // If this is a matrix, run column-by-column. + if (this.length > 1) { + tmpthis = tmpthis.transpose(); + for (; i < tmpthis.length; i++) + arr[i] = curriedFunction(tmpthis[i]); + return arr; + } + + // Otherwise run on the vector. + return curriedFunction(this[0]); + }; + })(funcs[i]); +})('quantiles percentileOfScore'.split(' ')); + +}(this.jStat, Math)); +// Special functions // +(function(jStat, Math) { + +// Log-gamma function +jStat.gammaln = function gammaln(x) { + var j = 0; + var cof = [ + 76.18009172947146, -86.50532032941677, 24.01409824083091, + -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5 + ]; + var ser = 1.000000000190015; + var xx, y, tmp; + tmp = (y = xx = x) + 5.5; + tmp -= (xx + 0.5) * Math.log(tmp); + for (; j < 6; j++) + ser += cof[j] / ++y; + return Math.log(2.5066282746310005 * ser / xx) - tmp; +}; + + +// gamma of x +jStat.gammafn = function gammafn(x) { + var p = [-1.716185138865495, 24.76565080557592, -379.80425647094563, + 629.3311553128184, 866.9662027904133, -31451.272968848367, + -36144.413418691176, 66456.14382024054 + ]; + var q = [-30.8402300119739, 315.35062697960416, -1015.1563674902192, + -3107.771671572311, 22538.118420980151, 4755.8462775278811, + -134659.9598649693, -115132.2596755535]; + var fact = false; + var n = 0; + var xden = 0; + var xnum = 0; + var y = x; + var i, z, yi, res, sum, ysq; + if (y <= 0) { + res = y % 1 + 3.6e-16; + if (res) { + fact = (!(y & 1) ? 1 : -1) * Math.PI / Math.sin(Math.PI * res); + y = 1 - y; + } else { + return Infinity; + } + } + yi = y; + if (y < 1) { + z = y++; + } else { + z = (y -= n = (y | 0) - 1) - 1; + } + for (i = 0; i < 8; ++i) { + xnum = (xnum + p[i]) * z; + xden = xden * z + q[i]; + } + res = xnum / xden + 1; + if (yi < y) { + res /= yi; + } else if (yi > y) { + for (i = 0; i < n; ++i) { + res *= y; + y++; + } + } + if (fact) { + res = fact / res; + } + return res; +}; + + +// lower incomplete gamma function P(a,x) +jStat.gammap = function gammap(a, x) { + var aln = jStat.gammaln(a); + var ap = a; + var sum = 1 / a; + var del = sum; + var b = x + 1 - a; + var c = 1 / 1.0e-30; + var d = 1 / b; + var h = d; + var i = 1; + // calculate maximum number of itterations required for a + var ITMAX = -~(Math.log((a >= 1) ? a : 1 / a) * 8.5 + a * 0.4 + 17); + var an, endval; + + if (x < 0 || a <= 0) { + return NaN; + } else if (x < a + 1) { + for (; i <= ITMAX; i++) { + sum += del *= x / ++ap; + } + return sum * Math.exp(-x + a * Math.log(x) - (aln)); + } + + for (; i <= ITMAX; i++) { + an = -i * (i - a); + b += 2; + d = an * d + b; + c = b + an / c; + d = 1 / d; + h *= d * c; + } + + return 1 - h * Math.exp(-x + a * Math.log(x) - (aln)); +}; + + +// natural log factorial of n +jStat.factorialln = function factorialln(n) { + return n < 0 ? NaN : jStat.gammaln(n + 1); +}; + +// factorial of n +jStat.factorial = function factorial(n) { + return n < 0 ? NaN : jStat.gammafn(n + 1); +}; + +// combinations of n, m +jStat.combination = function combination(n, m) { + // make sure n or m don't exceed the upper limit of usable values + return (n > 170 || m > 170) + ? Math.exp(jStat.combinationln(n, m)) + : (jStat.factorial(n) / jStat.factorial(m)) / jStat.factorial(n - m); +}; + + +jStat.combinationln = function combinationln(n, m){ + return jStat.factorialln(n) - jStat.factorialln(m) - jStat.factorialln(n - m); +}; + + +// permutations of n, m +jStat.permutation = function permutation(n, m) { + return jStat.factorial(n) / jStat.factorial(n - m); +}; + + +// beta function +jStat.betafn = function betafn(x, y) { + // ensure arguments are positive + if (x <= 0 || y <= 0) + return undefined; + // make sure x + y doesn't exceed the upper limit of usable values + return (x + y > 170) + ? Math.exp(jStat.betaln(x, y)) + : jStat.gammafn(x) * jStat.gammafn(y) / jStat.gammafn(x + y); +}; + + +// natural logarithm of beta function +jStat.betaln = function betaln(x, y) { + return jStat.gammaln(x) + jStat.gammaln(y) - jStat.gammaln(x + y); +}; + + +// Evaluates the continued fraction for incomplete beta function by modified +// Lentz's method. +jStat.betacf = function betacf(x, a, b) { + var fpmin = 1e-30; + var m = 1; + var qab = a + b; + var qap = a + 1; + var qam = a - 1; + var c = 1; + var d = 1 - qab * x / qap; + var m2, aa, del, h; + + // These q's will be used in factors that occur in the coefficients + if (Math.abs(d) < fpmin) + d = fpmin; + d = 1 / d; + h = d; + + for (; m <= 100; m++) { + m2 = 2 * m; + aa = m * (b - m) * x / ((qam + m2) * (a + m2)); + // One step (the even one) of the recurrence + d = 1 + aa * d; + if (Math.abs(d) < fpmin) + d = fpmin; + c = 1 + aa / c; + if (Math.abs(c) < fpmin) + c = fpmin; + d = 1 / d; + h *= d * c; + aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)); + // Next step of the recurrence (the odd one) + d = 1 + aa * d; + if (Math.abs(d) < fpmin) + d = fpmin; + c = 1 + aa / c; + if (Math.abs(c) < fpmin) + c = fpmin; + d = 1 / d; + del = d * c; + h *= del; + if (Math.abs(del - 1.0) < 3e-7) + break; + } + + return h; +}; + + +// Returns the inverse incomplte gamma function +jStat.gammapinv = function gammapinv(p, a) { + var j = 0; + var a1 = a - 1; + var EPS = 1e-8; + var gln = jStat.gammaln(a); + var x, err, t, u, pp, lna1, afac; + + if (p >= 1) + return Math.max(100, a + 100 * Math.sqrt(a)); + if (p <= 0) + return 0; + if (a > 1) { + lna1 = Math.log(a1); + afac = Math.exp(a1 * (lna1 - 1) - gln); + pp = (p < 0.5) ? p : 1 - p; + t = Math.sqrt(-2 * Math.log(pp)); + x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t; + if (p < 0.5) + x = -x; + x = Math.max(1e-3, + a * Math.pow(1 - 1 / (9 * a) - x / (3 * Math.sqrt(a)), 3)); + } else { + t = 1 - a * (0.253 + a * 0.12); + if (p < t) + x = Math.pow(p / t, 1 / a); + else + x = 1 - Math.log(1 - (p - t) / (1 - t)); + } + + for(; j < 12; j++) { + if (x <= 0) + return 0; + err = jStat.gammap(a, x) - p; + if (a > 1) + t = afac * Math.exp(-(x - a1) + a1 * (Math.log(x) - lna1)); + else + t = Math.exp(-x + a1 * Math.log(x) - gln); + u = err / t; + x -= (t = u / (1 - 0.5 * Math.min(1, u * ((a - 1) / x - 1)))); + if (x <= 0) + x = 0.5 * (x + t); + if (Math.abs(t) < EPS * x) + break; + } + + return x; +}; + + +// Returns the error function erf(x) +jStat.erf = function erf(x) { + var cof = [-1.3026537197817094, 6.4196979235649026e-1, 1.9476473204185836e-2, + -9.561514786808631e-3, -9.46595344482036e-4, 3.66839497852761e-4, + 4.2523324806907e-5, -2.0278578112534e-5, -1.624290004647e-6, + 1.303655835580e-6, 1.5626441722e-8, -8.5238095915e-8, + 6.529054439e-9, 5.059343495e-9, -9.91364156e-10, + -2.27365122e-10, 9.6467911e-11, 2.394038e-12, + -6.886027e-12, 8.94487e-13, 3.13092e-13, + -1.12708e-13, 3.81e-16, 7.106e-15, + -1.523e-15, -9.4e-17, 1.21e-16, + -2.8e-17]; + var j = cof.length - 1; + var isneg = false; + var d = 0; + var dd = 0; + var t, ty, tmp, res; + + if (x < 0) { + x = -x; + isneg = true; + } + + t = 2 / (2 + x); + ty = 4 * t - 2; + + for(; j > 0; j--) { + tmp = d; + d = ty * d - dd + cof[j]; + dd = tmp; + } + + res = t * Math.exp(-x * x + 0.5 * (cof[0] + ty * d) - dd); + return isneg ? res - 1 : 1 - res; +}; + + +// Returns the complmentary error function erfc(x) +jStat.erfc = function erfc(x) { + return 1 - jStat.erf(x); +}; + + +// Returns the inverse of the complementary error function +jStat.erfcinv = function erfcinv(p) { + var j = 0; + var x, err, t, pp; + if (p >= 2) + return -100; + if (p <= 0) + return 100; + pp = (p < 1) ? p : 2 - p; + t = Math.sqrt(-2 * Math.log(pp / 2)); + x = -0.70711 * ((2.30753 + t * 0.27061) / + (1 + t * (0.99229 + t * 0.04481)) - t); + for (; j < 2; j++) { + err = jStat.erfc(x) - pp; + x += err / (1.12837916709551257 * Math.exp(-x * x) - x * err); + } + return (p < 1) ? x : -x; +}; + + +// Returns the inverse of the incomplete beta function +jStat.ibetainv = function ibetainv(p, a, b) { + var EPS = 1e-8; + var a1 = a - 1; + var b1 = b - 1; + var j = 0; + var lna, lnb, pp, t, u, err, x, al, h, w, afac; + if (p <= 0) + return 0; + if (p >= 1) + return 1; + if (a >= 1 && b >= 1) { + pp = (p < 0.5) ? p : 1 - p; + t = Math.sqrt(-2 * Math.log(pp)); + x = (2.30753 + t * 0.27061) / (1 + t* (0.99229 + t * 0.04481)) - t; + if (p < 0.5) + x = -x; + al = (x * x - 3) / 6; + h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1)); + w = (x * Math.sqrt(al + h) / h) - (1 / (2 * b - 1) - 1 / (2 * a - 1)) * + (al + 5 / 6 - 2 / (3 * h)); + x = a / (a + b * Math.exp(2 * w)); + } else { + lna = Math.log(a / (a + b)); + lnb = Math.log(b / (a + b)); + t = Math.exp(a * lna) / a; + u = Math.exp(b * lnb) / b; + w = t + u; + if (p < t / w) + x = Math.pow(a * w * p, 1 / a); + else + x = 1 - Math.pow(b * w * (1 - p), 1 / b); + } + afac = -jStat.gammaln(a) - jStat.gammaln(b) + jStat.gammaln(a + b); + for(; j < 10; j++) { + if (x === 0 || x === 1) + return x; + err = jStat.ibeta(x, a, b) - p; + t = Math.exp(a1 * Math.log(x) + b1 * Math.log(1 - x) + afac); + u = err / t; + x -= (t = u / (1 - 0.5 * Math.min(1, u * (a1 / x - b1 / (1 - x))))); + if (x <= 0) + x = 0.5 * (x + t); + if (x >= 1) + x = 0.5 * (x + t + 1); + if (Math.abs(t) < EPS * x && j > 0) + break; + } + return x; +}; + + +// Returns the incomplete beta function I_x(a,b) +jStat.ibeta = function ibeta(x, a, b) { + // Factors in front of the continued fraction. + var bt = (x === 0 || x === 1) ? 0 : + Math.exp(jStat.gammaln(a + b) - jStat.gammaln(a) - + jStat.gammaln(b) + a * Math.log(x) + b * + Math.log(1 - x)); + if (x < 0 || x > 1) + return false; + if (x < (a + 1) / (a + b + 2)) + // Use continued fraction directly. + return bt * jStat.betacf(x, a, b) / a; + // else use continued fraction after making the symmetry transformation. + return 1 - bt * jStat.betacf(1 - x, b, a) / b; +}; + + +// Returns a normal deviate (mu=0, sigma=1). +// If n and m are specified it returns a object of normal deviates. +jStat.randn = function randn(n, m) { + var u, v, x, y, q, mat; + if (!m) + m = n; + if (n) + return jStat.create(n, m, function() { return jStat.randn(); }); + do { + u = Math.random(); + v = 1.7156 * (Math.random() - 0.5); + x = u - 0.449871; + y = Math.abs(v) + 0.386595; + q = x * x + y * (0.19600 * y - 0.25472 * x); + } while (q > 0.27597 && (q > 0.27846 || v * v > -4 * Math.log(u) * u * u)); + return v / u; +}; + + +// Returns a gamma deviate by the method of Marsaglia and Tsang. +jStat.randg = function randg(shape, n, m) { + var oalph = shape; + var a1, a2, u, v, x, mat; + if (!m) + m = n; + if (!shape) + shape = 1; + if (n) { + mat = jStat.zeros(n,m); + mat.alter(function() { return jStat.randg(shape); }); + return mat; + } + if (shape < 1) + shape += 1; + a1 = shape - 1 / 3; + a2 = 1 / Math.sqrt(9 * a1); + do { + do { + x = jStat.randn(); + v = 1 + a2 * x; + } while(v <= 0); + v = v * v * v; + u = Math.random(); + } while(u > 1 - 0.331 * Math.pow(x, 4) && + Math.log(u) > 0.5 * x*x + a1 * (1 - v + Math.log(v))); + // alpha > 1 + if (shape == oalph) + return a1 * v; + // alpha < 1 + do { + u = Math.random(); + } while(u === 0); + return Math.pow(u, 1 / oalph) * a1 * v; +}; + + +// making use of static methods on the instance +(function(funcs) { + for (var i = 0; i < funcs.length; i++) (function(passfunc) { + jStat.fn[passfunc] = function() { + return jStat( + jStat.map(this, function(value) { return jStat[passfunc](value); })); + } + })(funcs[i]); +})('gammaln gammafn factorial factorialln'.split(' ')); + + +(function(funcs) { + for (var i = 0; i < funcs.length; i++) (function(passfunc) { + jStat.fn[passfunc] = function() { + return jStat(jStat[passfunc].apply(null, arguments)); + }; + })(funcs[i]); +})('randn'.split(' ')); + +}(this.jStat, Math)); +(function(jStat, Math) { + +// generate all distribution instance methods +(function(list) { + for (var i = 0; i < list.length; i++) (function(func) { + // distribution instance method + jStat[func] = function(a, b, c) { + if (!(this instanceof arguments.callee)) + return new arguments.callee(a, b, c); + this._a = a; + this._b = b; + this._c = c; + return this; + }; + // distribution method to be used on a jStat instance + jStat.fn[func] = function(a, b, c) { + var newthis = jStat[func](a, b, c); + newthis.data = this; + return newthis; + }; + // sample instance method + jStat[func].prototype.sample = function(arr) { + var a = this._a; + var b = this._b; + var c = this._c; + if (arr) + return jStat.alter(arr, function() { + return jStat[func].sample(a, b, c); + }); + else + return jStat[func].sample(a, b, c); + }; + // generate the pdf, cdf and inv instance methods + (function(vals) { + for (var i = 0; i < vals.length; i++) (function(fnfunc) { + jStat[func].prototype[fnfunc] = function(x) { + var a = this._a; + var b = this._b; + var c = this._c; + if (!x && x !== 0) + x = this.data; + if (typeof x !== 'number') { + return jStat.fn.map.call(x, function(x) { + return jStat[func][fnfunc](x, a, b, c); + }); + } + return jStat[func][fnfunc](x, a, b, c); + }; + })(vals[i]); + })('pdf cdf inv'.split(' ')); + // generate the mean, median, mode and variance instance methods + (function(vals) { + for (var i = 0; i < vals.length; i++) (function(fnfunc) { + jStat[func].prototype[fnfunc] = function() { + return jStat[func][fnfunc](this._a, this._b, this._c); + }; + })(vals[i]); + })('mean median mode variance'.split(' ')); + })(list[i]); +})(( + 'beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy ' + + 'lognormal normal pareto studentt weibull uniform binomial negbin hypgeom ' + + 'poisson triangular' +).split(' ')); + + + +// extend beta function with static methods +jStat.extend(jStat.beta, { + pdf: function pdf(x, alpha, beta) { + // PDF is zero outside the support + if (x > 1 || x < 0) + return 0; + // PDF is one for the uniform case + if (alpha == 1 && beta == 1) + return 1; + + if (alpha < 512 || beta < 512) { + return (Math.pow(x, alpha - 1) * Math.pow(1 - x, beta - 1)) / + jStat.betafn(alpha, beta); + } else { + return Math.exp((alpha - 1) * Math.log(x) + + (beta - 1) * Math.log(1 - x) - + jStat.betaln(alpha, beta)); + } + }, + + cdf: function cdf(x, alpha, beta) { + return (x > 1 || x < 0) ? (x > 1) * 1 : jStat.ibeta(x, alpha, beta); + }, + + inv: function inv(x, alpha, beta) { + return jStat.ibetainv(x, alpha, beta); + }, + + mean: function mean(alpha, beta) { + return alpha / (alpha + beta); + }, + + median: function median(alpha, beta) { + throw new Error('median not yet implemented'); + }, + + mode: function mode(alpha, beta) { + return (alpha * beta) / (Math.pow(alpha + beta, 2) * (alpha + beta + 1)); + }, + + // return a random sample + sample: function sample(alpha, beta) { + var u = jStat.randg(alpha); + return u / (u + jStat.randg(beta)); + }, + + variance: function variance(alpha, beta) { + return (alpha * beta) / (Math.pow(alpha + beta, 2) * (alpha + beta + 1)); + } +}); + +// extend F function with static methods +jStat.extend(jStat.centralF, { + pdf: function pdf(x, df1, df2) { + if (x < 0) + return undefined; + return Math.sqrt((Math.pow(df1 * x, df1) * Math.pow(df2, df2)) / + (Math.pow(df1 * x + df2, df1 + df2))) / + (x * jStat.betafn(df1/2, df2/2)); + + }, + + cdf: function cdf(x, df1, df2) { + return jStat.ibeta((df1 * x) / (df1 * x + df2), df1 / 2, df2 / 2); + }, + + inv: function inv(x, df1, df2) { + return df2 / (df1 * (1 / jStat.ibetainv(x, df1 / 2, df2 / 2) - 1)); + }, + + mean: function mean(df1, df2) { + return (df2 > 2) ? df2 / (df2 - 2) : undefined; + }, + + mode: function mode(df1, df2) { + return (df1 > 2) ? (df2 * (df1 - 2)) / (df1 * (df2 + 2)) : undefined; + }, + + // return a random sample + sample: function sample(df1, df2) { + var x1 = jStat.randg(df1 / 2) * 2; + var x2 = jStat.randg(df2 / 2) * 2; + return (x1 / df1) / (x2 / df2); + }, + + variance: function variance(df1, df2) { + if (df2 <= 4) + return undefined; + return 2 * df2 * df2 * (df1 + df2 - 2) / + (df1 * (df2 - 2) * (df2 - 2) * (df2 - 4)); + } +}); + + +// extend cauchy function with static methods +jStat.extend(jStat.cauchy, { + pdf: function pdf(x, local, scale) { + return (scale / (Math.pow(x - local, 2) + Math.pow(scale, 2))) / Math.PI; + }, + + cdf: function cdf(x, local, scale) { + return Math.atan((x - local) / scale) / Math.PI + 0.5; + }, + + inv: function(p, local, scale) { + return local + scale * Math.tan(Math.PI * (p - 0.5)); + }, + + median: function median(local, scale) { + return local; + }, + + mode: function mode(local, scale) { + return local; + }, + + sample: function sample(local, scale) { + return jStat.randn() * + Math.sqrt(1 / (2 * jStat.randg(0.5))) * scale + local; + } +}); + + + +// extend chisquare function with static methods +jStat.extend(jStat.chisquare, { + pdf: function pdf(x, dof) { + return Math.exp((dof / 2 - 1) * Math.log(x) - x / 2 - (dof / 2) * + Math.log(2) - jStat.gammaln(dof / 2)); + }, + + cdf: function cdf(x, dof) { + return jStat.gammap(dof / 2, x / 2); + }, + + inv: function(p, dof) { + return 2 * jStat.gammapinv(p, 0.5 * dof); + }, + + mean : function(dof) { + return dof; + }, + + // TODO: this is an approximation (is there a better way?) + median: function median(dof) { + return dof * Math.pow(1 - (2 / (9 * dof)), 3); + }, + + mode: function mode(dof) { + return (dof - 2 > 0) ? dof - 2 : 0; + }, + + sample: function sample(dof) { + return jStat.randg(dof / 2) * 2; + }, + + variance: function variance(dof) { + return 2 * dof; + } +}); + + + +// extend exponential function with static methods +jStat.extend(jStat.exponential, { + pdf: function pdf(x, rate) { + return x < 0 ? 0 : rate * Math.exp(-rate * x); + }, + + cdf: function cdf(x, rate) { + return x < 0 ? 0 : 1 - Math.exp(-rate * x); + }, + + inv: function(p, rate) { + return -Math.log(1 - p) / rate; + }, + + mean : function(rate) { + return 1 / rate; + }, + + median: function (rate) { + return (1 / rate) * Math.log(2); + }, + + mode: function mode(rate) { + return 0; + }, + + sample: function sample(rate) { + return -1 / rate * Math.log(Math.random()); + }, + + variance : function(rate) { + return Math.pow(rate, -2); + } +}); + + + +// extend gamma function with static methods +jStat.extend(jStat.gamma, { + pdf: function pdf(x, shape, scale) { + return Math.exp((shape - 1) * Math.log(x) - x / scale - + jStat.gammaln(shape) - shape * Math.log(scale)); + }, + + cdf: function cdf(x, shape, scale) { + return jStat.gammap(shape, x / scale); + }, + + inv: function(p, shape, scale) { + return jStat.gammapinv(p, shape) * scale; + }, + + mean : function(shape, scale) { + return shape * scale; + }, + + mode: function mode(shape, scale) { + if(shape > 1) return (shape - 1) * scale; + return undefined; + }, + + sample: function sample(shape, scale) { + return jStat.randg(shape) * scale; + }, + + variance: function variance(shape, scale) { + return shape * scale * scale; + } +}); + +// extend inverse gamma function with static methods +jStat.extend(jStat.invgamma, { + pdf: function pdf(x, shape, scale) { + return Math.exp(-(shape + 1) * Math.log(x) - scale / x - + jStat.gammaln(shape) + shape * Math.log(scale)); + }, + + cdf: function cdf(x, shape, scale) { + return 1 - jStat.gammap(shape, scale / x); + }, + + inv: function(p, shape, scale) { + return scale / jStat.gammapinv(1 - p, shape); + }, + + mean : function(shape, scale) { + return (shape > 1) ? scale / (shape - 1) : undefined; + }, + + mode: function mode(shape, scale) { + return scale / (shape + 1); + }, + + sample: function sample(shape, scale) { + return scale / jStat.randg(shape); + }, + + variance: function variance(shape, scale) { + if (shape <= 2) + return undefined; + return scale * scale / ((shape - 1) * (shape - 1) * (shape - 2)); + } +}); + + +// extend kumaraswamy function with static methods +jStat.extend(jStat.kumaraswamy, { + pdf: function pdf(x, alpha, beta) { + return Math.exp(Math.log(alpha) + Math.log(beta) + (alpha - 1) * + Math.log(x) + (beta - 1) * + Math.log(1 - Math.pow(x, alpha))); + }, + + cdf: function cdf(x, alpha, beta) { + return (1 - Math.pow(1 - Math.pow(x, alpha), beta)); + }, + + mean : function(alpha, beta) { + return (beta * jStat.gammafn(1 + 1 / alpha) * + jStat.gammafn(beta)) / (jStat.gammafn(1 + 1 / alpha + beta)); + }, + + median: function median(alpha, beta) { + return Math.pow(1 - Math.pow(2, -1 / beta), 1 / alpha); + }, + + mode: function mode(alpha, beta) { + if (!(alpha >= 1 && beta >= 1 && (alpha !== 1 && beta !== 1))) + return undefined; + return Math.pow((alpha - 1) / (alpha * beta - 1), 1 / alpha); + }, + + variance: function variance(alpha, beta) { + throw new Error('variance not yet implemented'); + // TODO: complete this + } +}); + + + +// extend lognormal function with static methods +jStat.extend(jStat.lognormal, { + pdf: function pdf(x, mu, sigma) { + return Math.exp(-Math.log(x) - 0.5 * Math.log(2 * Math.PI) - + Math.log(sigma) - Math.pow(Math.log(x) - mu, 2) / + (2 * sigma * sigma)); + }, + + cdf: function cdf(x, mu, sigma) { + return 0.5 + + (0.5 * jStat.erf((Math.log(x) - mu) / Math.sqrt(2 * sigma * sigma))); + }, + + inv: function(p, mu, sigma) { + return Math.exp(-1.41421356237309505 * sigma * jStat.erfcinv(2 * p) + mu); + }, + + mean: function mean(mu, sigma) { + return Math.exp(mu + sigma * sigma / 2); + }, + + median: function median(mu, sigma) { + return Math.exp(mu); + }, + + mode: function mode(mu, sigma) { + return Math.exp(mu - sigma * sigma); + }, + + sample: function sample(mu, sigma) { + return Math.exp(jStat.randn() * sigma + mu); + }, + + variance: function variance(mu, sigma) { + return (Math.exp(sigma * sigma) - 1) * Math.exp(2 * mu + sigma * sigma); + } +}); + + + +// extend normal function with static methods +jStat.extend(jStat.normal, { + pdf: function pdf(x, mean, std) { + return Math.exp(-0.5 * Math.log(2 * Math.PI) - + Math.log(std) - Math.pow(x - mean, 2) / (2 * std * std)); + }, + + cdf: function cdf(x, mean, std) { + return 0.5 * (1 + jStat.erf((x - mean) / Math.sqrt(2 * std * std))); + }, + + inv: function(p, mean, std) { + return -1.41421356237309505 * std * jStat.erfcinv(2 * p) + mean; + }, + + mean : function(mean, std) { + return mean; + }, + + median: function median(mean, std) { + return mean; + }, + + mode: function (mean, std) { + return mean; + }, + + sample: function sample(mean, std) { + return jStat.randn() * std + mean; + }, + + variance : function(mean, std) { + return std * std; + } +}); + + + +// extend pareto function with static methods +jStat.extend(jStat.pareto, { + pdf: function pdf(x, scale, shape) { + if (x <= scale) + return undefined; + return (shape * Math.pow(scale, shape)) / Math.pow(x, shape + 1); + }, + + cdf: function cdf(x, scale, shape) { + return 1 - Math.pow(scale / x, shape); + }, + + mean: function mean(scale, shape) { + if (shape <= 1) + return undefined; + return (shape * Math.pow(scale, shape)) / (shape - 1); + }, + + median: function median(scale, shape) { + return scale * (shape * Math.SQRT2); + }, + + mode: function mode(scale, shape) { + return scale; + }, + + variance : function(scale, shape) { + if (shape <= 2) + return undefined; + return (scale*scale * shape) / (Math.pow(shape - 1, 2) * (shape - 2)); + } +}); + + + +// extend studentt function with static methods +jStat.extend(jStat.studentt, { + pdf: function pdf(x, dof) { + return (jStat.gammafn((dof + 1) / 2) / (Math.sqrt(dof * Math.PI) * + jStat.gammafn(dof / 2))) * + Math.pow(1 + ((x * x) / dof), -((dof + 1) / 2)); + }, + + cdf: function cdf(x, dof) { + var dof2 = dof / 2; + return jStat.ibeta((x + Math.sqrt(x * x + dof)) / + (2 * Math.sqrt(x * x + dof)), dof2, dof2); + }, + + inv: function(p, dof) { + var x = jStat.ibetainv(2 * Math.min(p, 1 - p), 0.5 * dof, 0.5); + x = Math.sqrt(dof * (1 - x) / x); + return (p > 0) ? x : -x; + }, + + mean: function mean(dof) { + return (dof > 1) ? 0 : undefined; + }, + + median: function median(dof) { + return 0; + }, + + mode: function mode(dof) { + return 0; + }, + + sample: function sample(dof) { + return jStat.randn() * Math.sqrt(dof / (2 * jStat.randg(dof / 2))); + }, + + variance: function variance(dof) { + return (dof > 2) ? dof / (dof - 2) : (dof > 1) ? Infinity : undefined; + } +}); + + + +// extend weibull function with static methods +jStat.extend(jStat.weibull, { + pdf: function pdf(x, scale, shape) { + if (x < 0) + return 0; + return (shape / scale) * Math.pow((x / scale), (shape - 1)) * + Math.exp(-(Math.pow((x / scale), shape))); + }, + + cdf: function cdf(x, scale, shape) { + return x < 0 ? 0 : 1 - Math.exp(-Math.pow((x / scale), shape)); + }, + + inv: function(p, scale, shape) { + return scale * Math.pow(-Math.log(1 - p), 1 / shape); + }, + + mean : function(scale, shape) { + return scale * jStat.gammafn(1 + 1 / shape); + }, + + median: function median(scale, shape) { + return scale * Math.pow(Math.log(2), 1 / shape); + }, + + mode: function mode(scale, shape) { + if (shape <= 1) + return undefined; + return scale * Math.pow((shape - 1) / shape, 1 / shape); + }, + + sample: function sample(scale, shape) { + return scale * Math.pow(-Math.log(Math.random()), 1 / shape); + }, + + variance: function variance(scale, shape) { + return scale * scale * jStat.gammafn(1 + 2 / shape) - + Math.pow(this.mean(scale, shape), 2); + } +}); + + + +// extend uniform function with static methods +jStat.extend(jStat.uniform, { + pdf: function pdf(x, a, b) { + return (x < a || x > b) ? 0 : 1 / (b - a); + }, + + cdf: function cdf(x, a, b) { + if (x < a) + return 0; + else if (x < b) + return (x - a) / (b - a); + return 1; + }, + + mean: function mean(a, b) { + return 0.5 * (a + b); + }, + + median: function median(a, b) { + return jStat.mean(a, b); + }, + + mode: function mode(a, b) { + throw new Error('mode is not yet implemented'); + }, + + sample: function sample(a, b) { + return (a / 2 + b / 2) + (b / 2 - a / 2) * (2 * Math.random() - 1); + }, + + variance: function variance(a, b) { + return Math.pow(b - a, 2) / 12; + } +}); + + + +// extend uniform function with static methods +jStat.extend(jStat.binomial, { + pdf: function pdf(k, n, p) { + return (p === 0 || p === 1) ? + ((n * p) === k ? 1 : 0) : + jStat.combination(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k); + }, + + cdf: function cdf(x, n, p) { + var binomarr = [], + k = 0; + if (x < 0) { + return 0; + } + if (x < n) { + for (; k <= x; k++) { + binomarr[ k ] = jStat.binomial.pdf(k, n, p); + } + return jStat.sum(binomarr); + } + return 1; + } +}); + + + +// extend uniform function with static methods +jStat.extend(jStat.negbin, { + pdf: function pdf(k, r, p) { + return k !== k | 0 + ? false + : k < 0 + ? 0 + : jStat.combination(k + r - 1, r - 1) * Math.pow(1 - p, k) * Math.pow(p, r); + }, + + cdf: function cdf(x, r, p) { + var sum = 0, + k = 0; + if (x < 0) return 0; + for (; k <= x; k++) { + sum += jStat.negbin.pdf(k, r, p); + } + return sum; + } +}); + + + +// extend uniform function with static methods +jStat.extend(jStat.hypgeom, { + pdf: function pdf(k, N, m, n) { + // Hypergeometric PDF. + + // A simplification of the CDF algorithm below. + + // k = number of successes drawn + // N = population size + // m = number of successes in population + // n = number of items drawn from population + + if(k !== k | 0) { + return false; + } else if(k < 0 || k < m - (N - n)) { + // It's impossible to have this few successes drawn. + return 0; + } else if(k > n || k > m) { + // It's impossible to have this many successes drawn. + return 0; + } else if (m * 2 > N) { + // More than half the population is successes. + + if(n * 2 > N) { + // More than half the population is sampled. + + return jStat.hypgeom.pdf(N - m - n + k, N, N - m, N - n) + } else { + // Half or less of the population is sampled. + + return jStat.hypgeom.pdf(n - k, N, N - m, n); + } + + } else if(n * 2 > N) { + // Half or less is successes. + + return jStat.hypgeom.pdf(m - k, N, m, N - n); + + } else if(m < n) { + // We want to have the number of things sampled to be less than the + // successes available. So swap the definitions of successful and sampled. + return jStat.hypgeom.pdf(k, N, n, m); + } else { + // If we get here, half or less of the population was sampled, half or + // less of it was successes, and we had fewer sampled things than + // successes. Now we can do this complicated iterative algorithm in an + // efficient way. + + // The basic premise of the algorithm is that we partially normalize our + // intermediate product to keep it in a numerically good region, and then + // finish the normalization at the end. + + // This variable holds the scaled probability of the current number of + // successes. + var scaledPDF = 1; + + // This keeps track of how much we have normalized. + var samplesDone = 0; + + for(var i = 0; i < k; i++) { + // For every possible number of successes up to that observed... + + while(scaledPDF > 1 && samplesDone < n) { + // Intermediate result is growing too big. Apply some of the + // normalization to shrink everything. + + scaledPDF *= 1 - (m / (N - samplesDone)); + + // Say we've normalized by this sample already. + samplesDone++; + } + + // Work out the partially-normalized hypergeometric PDF for the next + // number of successes + scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1)); + } + + for(; samplesDone < n; samplesDone++) { + // Apply all the rest of the normalization + scaledPDF *= 1 - (m / (N - samplesDone)); + } + + // Bound answer sanely before returning. + return Math.min(1, Math.max(0, scaledPDF)); + } + }, + + cdf: function cdf(x, N, m, n) { + // Hypergeometric CDF. + + // This algorithm is due to Prof. Thomas S. Ferguson, , + // and comes from his hypergeometric test calculator at + // . + + // x = number of successes drawn + // N = population size + // m = number of successes in population + // n = number of items drawn from population + + if(x < 0 || x < m - (N - n)) { + // It's impossible to have this few successes drawn or fewer. + return 0; + } else if(x >= n || x >= m) { + // We will always have this many successes or fewer. + return 1; + } else if (m * 2 > N) { + // More than half the population is successes. + + if(n * 2 > N) { + // More than half the population is sampled. + + return jStat.hypgeom.cdf(N - m - n + x, N, N - m, N - n) + } else { + // Half or less of the population is sampled. + + return 1 - jStat.hypgeom.cdf(n - x - 1, N, N - m, n); + } + + } else if(n * 2 > N) { + // Half or less is successes. + + return 1 - jStat.hypgeom.cdf(m - x - 1, N, m, N - n); + + } else if(m < n) { + // We want to have the number of things sampled to be less than the + // successes available. So swap the definitions of successful and sampled. + return jStat.hypgeom.cdf(x, N, n, m); + } else { + // If we get here, half or less of the population was sampled, half or + // less of it was successes, and we had fewer sampled things than + // successes. Now we can do this complicated iterative algorithm in an + // efficient way. + + // The basic premise of the algorithm is that we partially normalize our + // intermediate sum to keep it in a numerically good region, and then + // finish the normalization at the end. + + // Holds the intermediate, scaled total CDF. + var scaledCDF = 1; + + // This variable holds the scaled probability of the current number of + // successes. + var scaledPDF = 1; + + // This keeps track of how much we have normalized. + var samplesDone = 0; + + for(var i = 0; i < x; i++) { + // For every possible number of successes up to that observed... + + while(scaledCDF > 1 && samplesDone < n) { + // Intermediate result is growing too big. Apply some of the + // normalization to shrink everything. + + var factor = 1 - (m / (N - samplesDone)); + + scaledPDF *= factor; + scaledCDF *= factor; + + // Say we've normalized by this sample already. + samplesDone++; + } + + // Work out the partially-normalized hypergeometric PDF for the next + // number of successes + scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1)); + + // Add to the CDF answer. + scaledCDF += scaledPDF; + } + + for(; samplesDone < n; samplesDone++) { + // Apply all the rest of the normalization + scaledCDF *= 1 - (m / (N - samplesDone)); + } + + // Bound answer sanely before returning. + return Math.min(1, Math.max(0, scaledCDF)); + } + } +}); + + + +// extend uniform function with static methods +jStat.extend(jStat.poisson, { + pdf: function pdf(k, l) { + return Math.pow(l, k) * Math.exp(-l) / jStat.factorial(k); + }, + + cdf: function cdf(x, l) { + var sumarr = [], + k = 0; + if (x < 0) return 0; + for (; k <= x; k++) { + sumarr.push(jStat.poisson.pdf(k, l)); + } + return jStat.sum(sumarr); + }, + + mean : function(l) { + return l; + }, + + variance : function(l) { + return l; + }, + + sample: function sample(l) { + var p = 1, k = 0, L = Math.exp(-l); + do { + k++; + p *= Math.random(); + } while (p > L); + return k - 1; + } +}); + +// extend triangular function with static methods +jStat.extend(jStat.triangular, { + pdf: function pdf(x, a, b, c) { + return (b <= a || c < a || c > b) + ? undefined + : (x < a || x > b) + ? 0 + : (x <= c) + ? (2 * (x - a)) / ((b - a) * (c - a)) + : (2 * (b - x)) / ((b - a) * (b - c)); + }, + + cdf: function cdf(x, a, b, c) { + if (b <= a || c < a || c > b) + return undefined; + if (x < a) { + return 0; + } else { + if (x <= c) + return Math.pow(x - a, 2) / ((b - a) * (c - a)); + return 1 - Math.pow(b - x, 2) / ((b - a) * (b - c)); + } + // never reach this + return 1; + }, + + mean: function mean(a, b, c) { + return (a + b + c) / 3; + }, + + median: function median(a, b, c) { + if (c <= (a + b) / 2) { + return b - Math.sqrt((b - a) * (b - c)) / Math.sqrt(2); + } else if (c > (a + b) / 2) { + return a + Math.sqrt((b - a) * (c - a)) / Math.sqrt(2); + } + }, + + mode: function mode(a, b, c) { + return c; + }, + + sample: function sample(a, b, c) { + var u = Math.random(); + if (u < ((c - a) / (b - a))) + return a + Math.sqrt(u * (b - a) * (c - a)) + return b - Math.sqrt((1 - u) * (b - a) * (b - c)); + }, + + variance: function variance(a, b, c) { + return (a * a + b * b + c * c - a * b - a * c - b * c) / 18; + } +}); + +}(this.jStat, Math)); +/* Provides functions for the solution of linear system of equations, integration, extrapolation, + * interpolation, eigenvalue problems, differential equations and PCA analysis. */ + +(function(jStat, Math) { + +var push = Array.prototype.push; +var isArray = jStat.utils.isArray; + +jStat.extend({ + + // add a vector/matrix to a vector/matrix or scalar + add: function add(arr, arg) { + // check if arg is a vector or scalar + if (isArray(arg)) { + if (!isArray(arg[0])) arg = [ arg ]; + return jStat.map(arr, function(value, row, col) { + return value + arg[row][col]; + }); + } + return jStat.map(arr, function(value) { return value + arg; }); + }, + + // subtract a vector or scalar from the vector + subtract: function subtract(arr, arg) { + // check if arg is a vector or scalar + if (isArray(arg)) { + if (!isArray(arg[0])) arg = [ arg ]; + return jStat.map(arr, function(value, row, col) { + return value - arg[row][col] || 0; + }); + } + return jStat.map(arr, function(value) { return value - arg; }); + }, + + // matrix division + divide: function divide(arr, arg) { + if (isArray(arg)) { + if (!isArray(arg[0])) arg = [ arg ]; + return jStat.multiply(arr, jStat.inv(arg)); + } + return jStat.map(arr, function(value) { return value / arg; }); + }, + + // matrix multiplication + multiply: function multiply(arr, arg) { + var row, col, nrescols, sum, + nrow = arr.length, + ncol = arr[0].length, + res = jStat.zeros(nrow, nrescols = (isArray(arg)) ? arg[0].length : ncol), + rescols = 0; + if (isArray(arg)) { + for (; rescols < nrescols; rescols++) { + for (row = 0; row < nrow; row++) { + sum = 0; + for (col = 0; col < ncol; col++) + sum += arr[row][col] * arg[col][rescols]; + res[row][rescols] = sum; + } + } + return (nrow === 1 && rescols === 1) ? res[0][0] : res; + } + return jStat.map(arr, function(value) { return value * arg; }); + }, + + // Returns the dot product of two matricies + dot: function dot(arr, arg) { + if (!isArray(arr[0])) arr = [ arr ]; + if (!isArray(arg[0])) arg = [ arg ]; + // convert column to row vector + var left = (arr[0].length === 1 && arr.length !== 1) ? jStat.transpose(arr) : arr, + right = (arg[0].length === 1 && arg.length !== 1) ? jStat.transpose(arg) : arg, + res = [], + row = 0, + nrow = left.length, + ncol = left[0].length, + sum, col; + for (; row < nrow; row++) { + res[row] = []; + sum = 0; + for (col = 0; col < ncol; col++) + sum += left[row][col] * right[row][col]; + res[row] = sum; + } + return (res.length === 1) ? res[0] : res; + }, + + // raise every element by a scalar + pow: function pow(arr, arg) { + return jStat.map(arr, function(value) { return Math.pow(value, arg); }); + }, + + // generate the absolute values of the vector + abs: function abs(arr) { + return jStat.map(arr, function(value) { return Math.abs(value); }); + }, + + // TODO: make compatible with matrices + // computes the p-norm of the vector + norm: function norm(arr, p) { + var nnorm = 0, + i = 0; + // check the p-value of the norm, and set for most common case + if (isNaN(p)) p = 2; + // check if multi-dimensional array, and make vector correction + if (isArray(arr[0])) arr = arr[0]; + // vector norm + for (; i < arr.length; i++) { + nnorm += Math.pow(Math.abs(arr[i]), p); + } + return Math.pow(nnorm, 1 / p); + }, + + // TODO: make compatible with matrices + // computes the angle between two vectors in rads + angle: function angle(arr, arg) { + return Math.acos(jStat.dot(arr, arg) / (jStat.norm(arr) * jStat.norm(arg))); + }, + + // augment one matrix by another + aug: function aug(a, b) { + var newarr = a.slice(), + i = 0; + for (; i < newarr.length; i++) { + push.apply(newarr[i], b[i]); + } + return newarr; + }, + + inv: function inv(a) { + var rows = a.length, + cols = a[0].length, + b = jStat.identity(rows, cols), + c = jStat.gauss_jordan(a, b), + obj = [], + i = 0, + j; + for (; i < rows; i++) { + obj[i] = []; + for (j = cols - 1; j < c[0].length; j++) + obj[i][j - cols] = c[i][j]; + } + return obj; + }, + + // calculate the determinant of a matrix + det: function det(a) { + var alen = a.length, + alend = alen * 2, + vals = new Array(alend), + rowshift = alen - 1, + colshift = alend - 1, + mrow = rowshift - alen + 1, + mcol = colshift, + i = 0, + result = 0, + j; + // check for special 2x2 case + if (alen === 2) { + return a[0][0] * a[1][1] - a[0][1] * a[1][0]; + } + for (; i < alend; i++) { + vals[i] = 1; + } + for (i = 0; i < alen; i++) { + for (j = 0; j < alen; j++) { + vals[(mrow < 0) ? mrow + alen : mrow ] *= a[i][j]; + vals[(mcol < alen) ? mcol + alen : mcol ] *= a[i][j]; + mrow++; + mcol--; + } + mrow = --rowshift - alen + 1; + mcol = --colshift; + } + for (i = 0; i < alen; i++) { + result += vals[i]; + } + for (; i < alend; i++) { + result -= vals[i]; + } + return result; + }, + + gauss_elimination: function gauss_elimination(a, b) { + var i = 0, + j = 0, + n = a.length, + m = a[0].length, + factor = 1, + sum = 0, + x = [], + maug, pivot, temp, k; + a = jStat.aug(a, b); + maug = a[0].length; + for(; i < n; i++) { + pivot = a[i][i]; + j = i; + for (k = i + 1; k < m; k++) { + if (pivot < Math.abs(a[k][i])) { + pivot = a[k][i]; + j = k; + } + } + if (j != i) { + for(k = 0; k < maug; k++) { + temp = a[i][k]; + a[i][k] = a[j][k]; + a[j][k] = temp; + } + } + for (j = i + 1; j < n; j++) { + factor = a[j][i] / a[i][i]; + for(k = i; k < maug; k++) { + a[j][k] = a[j][k] - factor * a[i][k]; + } + } + } + for (i = n - 1; i >= 0; i--) { + sum = 0; + for (j = i + 1; j<= n - 1; j++) { + sum = x[j] * a[i][j]; + } + x[i] =(a[i][maug - 1] - sum) / a[i][i]; + } + return x; + }, + + gauss_jordan: function gauss_jordan(a, b) { + var m = jStat.aug(a, b), + h = m.length, + w = m[0].length; + // find max pivot + for (var y = 0; y < h; y++) { + var maxrow = y; + for (var y2 = y+1; y2 < h; y2++) { + if (Math.abs(m[y2][y]) > Math.abs(m[maxrow][y])) + maxrow = y2; + } + var tmp = m[y]; + m[y] = m[maxrow]; + m[maxrow] = tmp + for (var y2 = y+1; y2 < h; y2++) { + c = m[y2][y] / m[y][y]; + for (var x = y; x < w; x++) { + m[y2][x] -= m[y][x] * c; + } + } + } + // backsubstitute + for (var y = h-1; y >= 0; y--) { + c = m[y][y]; + for (var y2 = 0; y2 < y; y2++) { + for (var x = w-1; x > y-1; x--) { + m[y2][x] -= m[y][x] * m[y2][y] / c; + } + } + m[y][y] /= c; + for (var x = h; x < w; x++) { + m[y][x] /= c; + } + } + return m; + }, + + lu: function lu(a, b) { + throw new Error('lu not yet implemented'); + }, + + cholesky: function cholesky(a, b) { + throw new Error('cholesky not yet implemented'); + }, + + gauss_jacobi: function gauss_jacobi(a, b, x, r) { + var i = 0; + var j = 0; + var n = a.length; + var l = []; + var u = []; + var d = []; + var xv, c, h, xk; + for (; i < n; i++) { + l[i] = []; + u[i] = []; + d[i] = []; + for (j = 0; j < n; j++) { + if (i > j) { + l[i][j] = a[i][j]; + u[i][j] = d[i][j] = 0; + } else if (i < j) { + u[i][j] = a[i][j]; + l[i][j] = d[i][j] = 0; + } else { + d[i][j] = a[i][j]; + l[i][j] = u[i][j] = 0; + } + } + } + h = jStat.multiply(jStat.multiply(jStat.inv(d), jStat.add(l, u)), -1); + c = jStat.multiply(jStat.inv(d), b); + xv = x; + xk = jStat.add(jStat.multiply(h, x), c); + i = 2; + while (Math.abs(jStat.norm(jStat.subtract(xk,xv))) > r) { + xv = xk; + xk = jStat.add(jStat.multiply(h, xv), c); + i++; + } + return xk; + }, + + gauss_seidel: function gauss_seidel(a, b, x, r) { + var i = 0; + var n = a.length; + var l = []; + var u = []; + var d = []; + var j, xv, c, h, xk; + for (; i < n; i++) { + l[i] = []; + u[i] = []; + d[i] = []; + for (j = 0; j < n; j++) { + if (i > j) { + l[i][j] = a[i][j]; + u[i][j] = d[i][j] = 0; + } else if (i < j) { + u[i][j] = a[i][j]; + l[i][j] = d[i][j] = 0; + } else { + d[i][j] = a[i][j]; + l[i][j] = u[i][j] = 0; + } + } + } + h = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d, l)), u), -1); + c = jStat.multiply(jStat.inv(jStat.add(d, l)), b); + xv = x; + xk = jStat.add(jStat.multiply(h, x), c); + i = 2; + while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) { + xv = xk; + xk = jStat.add(jStat.multiply(h, xv), c); + i = i + 1; + } + return xk; + }, + + SOR: function SOR(a, b, x, r, w) { + var i = 0; + var n = a.length; + var l = []; + var u = []; + var d = []; + var j, xv, c, h, xk; + for (; i < n; i++) { + l[i] = []; + u[i] = []; + d[i] = []; + for (j = 0; j < n; j++) { + if (i > j) { + l[i][j] = a[i][j]; + u[i][j] = d[i][j] = 0; + } else if (i < j) { + u[i][j] = a[i][j]; + l[i][j] = d[i][j] = 0; + } else { + d[i][j] = a[i][j]; + l[i][j] = u[i][j] = 0; + } + } + } + h = jStat.multiply(jStat.inv(jStat.add(d, jStat.multiply(l, w))), + jStat.subtract(jStat.multiply(d, 1 - w), + jStat.multiply(u, w))); + c = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d, + jStat.multiply(l, w))), b), w); + xv = x; + xk = jStat.add(jStat.multiply(h, x), c); + i = 2; + while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) { + xv = xk; + xk = jStat.add(jStat.multiply(h, xv), c); + i++; + } + return xk; + }, + + householder: function householder(a) { + var m = a.length; + var n = a[0].length; + var i = 0; + var w = []; + var p = []; + var alpha, r, k, j, factor; + for (; i < m - 1; i++) { + alpha = 0; + for (j = i + 1; j < n; j++) + alpha += (a[j][i] * a[j][i]); + factor = (a[i + 1][i] > 0) ? -1 : 1; + alpha = factor * Math.sqrt(alpha); + r = Math.sqrt((((alpha * alpha) - a[i + 1][i] * alpha) / 2)); + w = jStat.zeros(m, 1); + w[i + 1][0] = (a[i + 1][i] - alpha) / (2 * r); + for (k = i + 2; k < m; k++) w[k][0] = a[k][i] / (2 * r); + p = jStat.subtract(jStat.identity(m, n), + jStat.multiply(jStat.multiply(w, jStat.transpose(w)), 2)); + a = jStat.multiply(p, jStat.multiply(a, p)); + } + return a; + }, + + // TODO: not working properly. + QR: function QR(a, b) { + var m = a.length; + var n = a[0].length; + var i = 0; + var w = []; + var p = []; + var x = []; + var j, alpha, r, k, factor, sum; + for (; i < m - 1; i++) { + alpha = 0; + for (j = i + 1; j < n; j++) + alpha += (a[j][i] * a[j][i]); + factor = (a[i + 1][i] > 0) ? -1 : 1; + alpha = factor * Math.sqrt(alpha); + r = Math.sqrt((((alpha * alpha) - a[i + 1][i] * alpha) / 2)); + w = jStat.zeros(m, 1); + w[i + 1][0] = (a[i + 1][i] - alpha) / (2 * r); + for (k = i + 2; k < m; k++) + w[k][0] = a[k][i] / (2 * r); + p = jStat.subtract(jStat.identity(m, n), + jStat.multiply(jStat.multiply(w, jStat.transpose(w)), 2)); + a = jStat.multiply(p, a); + b = jStat.multiply(p, b); + } + for (i = m - 1; i >= 0; i--) { + sum = 0; + for (j = i + 1; j <= n - 1; j++) + sum = x[j] * a[i][j]; + x[i] = b[i][0] / a[i][i]; + } + return x; + }, + + jacobi: function jacobi(a) { + var condition = 1; + var count = 0; + var n = a.length; + var e = jStat.identity(n, n); + var ev = []; + var b, i, j, p, q, maxim, theta, s; + // condition === 1 only if tolerance is not reached + while (condition === 1) { + count++; + maxim = a[0][1]; + p = 0; + q = 1; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + if (i != j) { + if (maxim < Math.abs(a[i][j])) { + maxim = Math.abs(a[i][j]); + p = i; + q = j; + } + } + } + } + if (a[p][p] === a[q][q]) + theta = (a[p][q] > 0) ? Math.PI / 4 : -Math.PI / 4; + else + theta = Math.atan(2 * a[p][q] / (a[p][p] - a[q][q])) / 2; + s = jStat.identity(n, n); + s[p][p] = Math.cos(theta); + s[p][q] = -Math.sin(theta); + s[q][p] = Math.sin(theta); + s[q][q] = Math.cos(theta); + // eigen vector matrix + e = jStat.multiply(e, s); + b = jStat.multiply(jStat.multiply(jStat.inv(s), a), s); + a = b; + condition = 0; + for (i = 1; i < n; i++) { + for (j = 1; j < n; j++) { + if (i != j && Math.abs(a[i][j]) > 0.001) { + condition = 1; + } + } + } + } + for (i = 0; i < n; i++) ev.push(a[i][i]); + //returns both the eigenvalue and eigenmatrix + return [e, ev]; + }, + + rungekutta: function rungekutta(f, h, p, t_j, u_j, order) { + var k1, k2, u_j1, k3, k4; + if (order === 2) { + while (t_j <= p) { + k1 = h * f(t_j, u_j); + k2 = h * f(t_j + h, u_j + k1); + u_j1 = u_j + (k1 + k2) / 2; + u_j = u_j1; + t_j = t_j + h; + } + } + if (order === 4) { + while (t_j <= p) { + k1 = h * f(t_j, u_j); + k2 = h * f(t_j + h / 2, u_j + k1 / 2); + k3 = h * f(t_j + h / 2, u_j + k2 / 2); + k4 = h * f(t_j +h, u_j + k3); + u_j1 = u_j + (k1 + 2 * k2 + 2 * k3 + k4) / 6; + u_j = u_j1; + t_j = t_j + h; + } + } + return u_j; + }, + + romberg: function romberg(f, a, b, order) { + var i = 0; + var h = (b - a) / 2; + var x = []; + var h1 = []; + var g = []; + var m, a1, j, k, I, d; + while (i < order / 2) { + I = f(a); + for (j = a, k = 0; j <= b; j = j + h, k++) x[k] = j; + m = x.length; + for (j = 1; j < m - 1; j++) { + I += (((j % 2) !== 0) ? 4 : 2) * f(x[j]); + } + I = (h / 3) * (I + f(b)); + g[i] = I; + h /= 2; + i++; + } + a1 = g.length; + m = 1; + while (a1 !== 1) { + for (j = 0; j < a1 - 1; j++) + h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1); + a1 = h1.length; + g = h1; + h1 = []; + m++; + } + return g; + }, + + richardson: function richardson(X, f, x, h) { + function pos(X, x) { + var i = 0; + var n = X.length; + var p; + for (; i < n; i++) + if (X[i] === x) p = i; + return p; + } + var n = X.length, + h_min = Math.abs(x - X[pos(X, x) + 1]), + i = 0, + g = [], + h1 = [], + y1, y2, m, a, j; + while (h >= h_min) { + y1 = pos(X, x + h); + y2 = pos(X, x); + g[i] = (f[y1] - 2 * f[y2] + f[2 * y2 - y1]) / (h * h); + h /= 2; + i++; + } + a = g.length; + m = 1; + while (a != 1) { + for (j = 0; j < a - 1; j++) + h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1); + a = h1.length; + g = h1; + h1 = []; + m++; + } + return g; + }, + + simpson: function simpson(f, a, b, n) { + var h = (b - a) / n; + var I = f(a); + var x = []; + var j = a; + var k = 0; + var i = 1; + var m; + for (; j <= b; j = j + h, k++) + x[k] = j; + m = x.length; + for (; i < m - 1; i++) { + I += ((i % 2 !== 0) ? 4 : 2) * f(x[i]); + } + return (h / 3) * (I + f(b)); + }, + + hermite: function hermite(X, F, dF, value) { + var n = X.length; + var p = 0; + var i = 0; + var l = []; + var dl = []; + var A = []; + var B = []; + var j; + for (; i < n; i++) { + l[i] = 1; + for (j = 0; j < n; j++) { + if (i != j) l[i] *= (value - X[j]) / (X[i] - X[j]); + } + dl[i] = 0; + for (j = 0; j < n; j++) { + if (i != j) dl[i] += 1 / (X [i] - X[j]); + } + A[i] = (1 - 2 * (value - X[i]) * dl[i]) * (l[i] * l[i]); + B[i] = (value - X[i]) * (l[i] * l[i]); + p += (A[i] * F[i] + B[i] * dF[i]); + } + return p; + }, + + lagrange: function lagrange(X, F, value) { + var p = 0; + var i = 0; + var j, l; + var n = X.length; + for (; i < n; i++) { + l = F[i]; + for (j = 0; j < n; j++) { + // calculating the lagrange polynomial L_i + if (i != j) l *= (value - X[j]) / (X[i] - X[j]); + } + // adding the lagrange polynomials found above + p += l; + } + return p; + }, + + cubic_spline: function cubic_spline(X, F, value) { + var n = X.length; + var i = 0, j; + var A = []; + var B = []; + var alpha = []; + var c = []; + var h = []; + var b = []; + var d = []; + for (; i < n - 1; i++) + h[i] = X[i + 1] - X[i]; + alpha[0] = 0; + for (i = 1; i < n - 1; i++) { + alpha[i] = (3 / h[i]) * (F[i + 1] - F[i]) - + (3 / h[i-1]) * (F[i] - F[i-1]); + } + for (i = 1; i < n - 1; i++) { + A[i] = []; + B[i] = []; + A[i][i-1] = h[i-1]; + A[i][i] = 2 * (h[i - 1] + h[i]); + A[i][i+1] = h[i]; + B[i][0] = alpha[i]; + } + c = jStat.multiply(jStat.inv(A), B); + for (j = 0; j < n - 1; j++) { + b[j] = (F[j + 1] - F[j]) / h[j] - h[j] * (c[j + 1][0] + 2 * c[j][0]) / 3; + d[j] = (c[j + 1][0] - c[j][0]) / (3 * h[j]); + } + for (j = 0; j < n; j++) { + if (X[j] > value) break; + } + j -= 1; + return F[j] + (value - X[j]) * b[j] + jStat.sq(value-X[j]) * + c[j] + (value - X[j]) * jStat.sq(value - X[j]) * d[j]; + }, + + gauss_quadrature: function gauss_quadrature() { + throw new Error('gauss_quadrature not yet implemented'); + }, + + PCA: function PCA(X) { + var m = X.length; + var n = X[0].length; + var flag = false; + var i = 0; + var j, temp1; + var u = []; + var D = []; + var result = []; + var temp2 = []; + var Y = []; + var Bt = []; + var B = []; + var C = []; + var V = []; + var Vt = []; + for (i = 0; i < m; i++) { + u[i] = jStat.sum(X[i]) / n; + } + for (i = 0; i < n; i++) { + B[i] = []; + for(j = 0; j < m; j++) { + B[i][j] = X[j][i] - u[j]; + } + } + B = jStat.transpose(B); + for (i = 0; i < m; i++) { + C[i] = []; + for (j = 0; j < m; j++) { + C[i][j] = (jStat.dot([B[i]], [B[j]])) / (n - 1); + } + } + result = jStat.jacobi(C); + V = result[0]; + D = result[1]; + Vt = jStat.transpose(V); + for (i = 0; i < D.length; i++) { + for (j = i; j < D.length; j++) { + if(D[i] < D[j]) { + temp1 = D[i]; + D[i] = D[j]; + D[j] = temp1; + temp2 = Vt[i]; + Vt[i] = Vt[j]; + Vt[j] = temp2; + } + } + } + Bt = jStat.transpose(B); + for (i = 0; i < m; i++) { + Y[i] = []; + for (j = 0; j < Bt.length; j++) { + Y[i][j] = jStat.dot([Vt[i]], [Bt[j]]); + } + } + return [X, D, Vt, Y]; + } +}); + +// extend jStat.fn with methods that require one argument +(function(funcs) { + for (var i = 0; i < funcs.length; i++) (function(passfunc) { + jStat.fn[passfunc] = function(arg, func) { + var tmpthis = this; + // check for callback + if (func) { + setTimeout(function() { + func.call(tmpthis, jStat.fn[passfunc].call(tmpthis, arg)); + }, 15); + return this; + } + return jStat(jStat[passfunc](this, arg)); + }; + }(funcs[i])); +}('add divide multiply subtract dot pow abs norm angle'.split(' '))); + +}(this.jStat, Math)); +(function(jStat, Math) { + +var slice = [].slice; +var isNumber = jStat.utils.isNumber; + +// flag==true denotes use of sample standard deviation +// Z Statistics +jStat.extend({ + // 2 different parameter lists: + // (value, mean, sd) + // (value, array, flag) + zscore: function zscore() { + var args = slice.call(arguments); + if (isNumber(args[1])) { + return (args[0] - args[1]) / args[2]; + } + return (args[0] - jStat.mean(args[1])) / jStat.stdev(args[1], args[2]); + }, + + // 3 different paramter lists: + // (value, mean, sd, sides) + // (zscore, sides) + // (value, array, sides, flag) + ztest: function ztest() { + var args = slice.call(arguments); + if (args.length === 4) { + if(isNumber(args[1])) { + var z = jStat.zscore(args[0],args[1],args[2]) + return (args[3] === 1) ? + (jStat.normal.cdf(-Math.abs(z),0,1)) : + (jStat.normal.cdf(-Math.abs(z),0,1)* 2); + } + var z = args[0] + return (args[2] === 1) ? + (jStat.normal.cdf(-Math.abs(z),0,1)) : + (jStat.normal.cdf(-Math.abs(z),0,1)*2); + } + var z = jStat.zscore(args[0],args[1],args[3]) + return (args[1] === 1) ? + (jStat.normal.cdf(-Math.abs(z), 0, 1)) : + (jStat.normal.cdf(-Math.abs(z), 0, 1)*2); + } +}); + +jStat.extend(jStat.fn, { + zscore: function zscore(value, flag) { + return (value - this.mean()) / this.stdev(flag); + }, + + ztest: function ztest(value, sides, flag) { + var zscore = Math.abs(this.zscore(value, flag)); + return (sides === 1) ? + (jStat.normal.cdf(-zscore, 0, 1)) : + (jStat.normal.cdf(-zscore, 0, 1) * 2); + } +}); + +// T Statistics +jStat.extend({ + // 2 parameter lists + // (value, mean, sd, n) + // (value, array) + tscore: function tscore() { + var args = slice.call(arguments); + return (args.length === 4) ? + ((args[0] - args[1]) / (args[2] / Math.sqrt(args[3]))) : + ((args[0] - jStat.mean(args[1])) / + (jStat.stdev(args[1], true) / Math.sqrt(args[1].length))); + }, + + // 3 different paramter lists: + // (value, mean, sd, n, sides) + // (tscore, n, sides) + // (value, array, sides) + ttest: function ttest() { + var args = slice.call(arguments); + var tscore; + if (args.length === 5) { + tscore = Math.abs(jStat.tscore(args[0], args[1], args[2], args[3])); + return (args[4] === 1) ? + (jStat.studentt.cdf(-tscore, args[3]-1)) : + (jStat.studentt.cdf(-tscore, args[3]-1)*2); + } + if (isNumber(args[1])) { + tscore = Math.abs(args[0]) + return (args[2] == 1) ? + (jStat.studentt.cdf(-tscore, args[1]-1)) : + (jStat.studentt.cdf(-tscore, args[1]-1) * 2); + } + tscore = Math.abs(jStat.tscore(args[0], args[1])) + return (args[2] == 1) ? + (jStat.studentt.cdf(-tscore, args[1].length-1)) : + (jStat.studentt.cdf(-tscore, args[1].length-1) * 2); + } +}); + +jStat.extend(jStat.fn, { + tscore: function tscore(value) { + return (value - this.mean()) / (this.stdev(true) / Math.sqrt(this.cols())); + }, + + ttest: function ttest(value, sides) { + return (sides === 1) ? + (1 - jStat.studentt.cdf(Math.abs(this.tscore(value)), this.cols()-1)) : + (jStat.studentt.cdf(-Math.abs(this.tscore(value)), this.cols()-1)*2); + } +}); + +// F Statistics +jStat.extend({ + // Paramter list is as follows: + // (array1, array2, array3, ...) + // or it is an array of arrays + // array of arrays conversion + anovafscore: function anovafscore() { + var args = slice.call(arguments), + expVar, sample, sampMean, sampSampMean, tmpargs, unexpVar, i, j; + if (args.length === 1) { + tmpargs = new Array(args[0].length); + for (i = 0; i < args[0].length; i++) { + tmpargs[i] = args[0][i]; + } + args = tmpargs; + } + // 2 sample case + if (args.length === 2) { + return jStat.variance(args[0]) / jStat.variance(args[1]); + } + // Builds sample array + sample = new Array(); + for (i = 0; i < args.length; i++) { + sample = sample.concat(args[i]); + } + sampMean = jStat.mean(sample); + // Computes the explained variance + expVar = 0; + for (i = 0; i < args.length; i++) { + expVar = expVar + args[i].length * Math.pow(jStat.mean(args[i]) - sampMean, 2); + } + expVar /= (args.length - 1); + // Computes unexplained variance + unexpVar = 0; + for (i = 0; i < args.length; i++) { + sampSampMean = jStat.mean(args[i]); + for (j = 0; j < args[i].length; j++) { + unexpVar += Math.pow(args[i][j] - sampSampMean, 2); + } + } + unexpVar /= (sample.length - args.length); + return expVar / unexpVar; + }, + + // 2 different paramter setups + // (array1, array2, array3, ...) + // (anovafscore, df1, df2) + anovaftest: function anovaftest() { + var args = slice.call(arguments), + df1, df2, n, i; + if (isNumber(args[0])) { + return 1 - jStat.centralF.cdf(args[0], args[1], args[2]); + } + anovafscore = jStat.anovafscore(args); + df1 = args.length - 1; + n = 0; + for (i = 0; i < args.length; i++) { + n = n + args[i].length; + } + df2 = n - df1 - 1; + return 1 - jStat.centralF.cdf(anovafscore, df1, df2); + }, + + ftest: function ftest(fscore, df1, df2) { + return 1 - jStat.centralF.cdf(fscore, df1, df2); + } +}); + +jStat.extend(jStat.fn, { + anovafscore: function anovafscore() { + return jStat.anovafscore(this.toArray()); + }, + + anovaftes: function anovaftes() { + var n = 0; + var i; + for (i = 0; i < this.length; i++) { + n = n + this[i].length; + } + return jStat.ftest(this.anovafscore(), this.length - 1, n - this.length); + } +}); + +// Error Bounds +jStat.extend({ + // 2 different parameter setups + // (value, alpha, sd, n) + // (value, alpha, array) + normalci: function normalci() { + var args = slice.call(arguments), + ans = new Array(2), + change; + if (args.length === 4) { + change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) * + args[2] / Math.sqrt(args[3])); + } else { + change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) * + jStat.stdev(args[2]) / Math.sqrt(args[2].length)); + } + ans[0] = args[0] - change; + ans[1] = args[0] + change; + return ans; + }, + + // 2 different parameter setups + // (value, alpha, sd, n) + // (value, alpha, array) + tci: function tci() { + var args = slice.call(arguments), + ans = new Array(2), + change; + if (args.length === 4) { + change = Math.abs(jStat.studentt.inv(args[1] / 2, args[3] - 1) * + args[2] / Math.sqrt(args[3])); + } else { + change = Math.abs(jStat.studentt.inv(args[1] / 2, args[2].length - 1) * + jStat.stdev(args[2], true) / Math.sqrt(args[2].length)); + } + ans[0] = args[0] - change; + ans[1] = args[0] + change; + return ans; + }, + + significant: function significant(pvalue, alpha) { + return pvalue < alpha; + } +}); + +jStat.extend(jStat.fn, { + normalci: function normalci(value, alpha) { + return jStat.normalci(value, alpha, this.toArray()); + }, + + tci: function tci(value, alpha) { + return jStat.tci(value, alpha, this.toArray()); + } +}); + +}(this.jStat, Math)); diff --git a/vendor/assets/javascripts/lodash.js b/vendor/assets/javascripts/lodash.js new file mode 100644 index 000000000..4328fb876 --- /dev/null +++ b/vendor/assets/javascripts/lodash.js @@ -0,0 +1,6789 @@ +/** + * @license + * Lo-Dash 2.4.1 (Custom Build) + * Build: `lodash modern -o ./dist/lodash.js` + * Copyright 2012-2013 The Dojo Foundation + * Based on Underscore.js 1.5.2 + * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre ES5 environments */ + var undefined; + + /** Used to pool arrays and objects used internally */ + var arrayPool = [], + objectPool = []; + + /** Used to generate unique IDs */ + var idCounter = 0; + + /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ + var keyPrefix = +new Date + ''; + + /** Used as the size when optimizations are enabled for large arrays */ + var largeArraySize = 75; + + /** Used as the max size of the `arrayPool` and `objectPool` */ + var maxPoolSize = 40; + + /** Used to detect and test whitespace */ + var whitespace = ( + // whitespace + ' \t\x0B\f\xA0\ufeff' + + + // line terminators + '\n\r\u2028\u2029' + + + // unicode category "Zs" space separators + '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' + ); + + /** Used to match empty string literals in compiled template source */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** + * Used to match ES6 template delimiters + * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match regexp flags from their coerced string values */ + var reFlags = /\w*$/; + + /** Used to detected named functions */ + var reFuncName = /^\s*function[ \n\r\t]+\w/; + + /** Used to match "interpolate" template delimiters */ + var reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match leading whitespace and zeros to be removed */ + var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)'); + + /** Used to ensure capturing order of template delimiters */ + var reNoMatch = /($^)/; + + /** Used to detect functions containing a `this` reference */ + var reThis = /\bthis\b/; + + /** Used to match unescaped characters in compiled string literals */ + var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; + + /** Used to assign default `context` object properties */ + var contextProps = [ + 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', + 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', + 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify */ + var templateCounter = 0; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + /** Used to identify object classifications that `_.clone` supports */ + var cloneableClasses = {}; + cloneableClasses[funcClass] = false; + cloneableClasses[argsClass] = cloneableClasses[arrayClass] = + cloneableClasses[boolClass] = cloneableClasses[dateClass] = + cloneableClasses[numberClass] = cloneableClasses[objectClass] = + cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; + + /** Used as an internal `_.debounce` options object */ + var debounceOptions = { + 'leading': false, + 'maxWait': 0, + 'trailing': false + }; + + /** Used as the property descriptor for `__bindData__` */ + var descriptor = { + 'configurable': false, + 'enumerable': false, + 'value': null, + 'writable': false + }; + + /** Used to determine if values are of the language type Object */ + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + /** Used to escape characters for inclusion in compiled string literals */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Used as a reference to the global object */ + var root = (objectTypes[typeof window] && window) || this; + + /** Detect free variable `exports` */ + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + /** Detect free variable `module` */ + var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports` */ + var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; + + /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ + var freeGlobal = objectTypes[typeof global] && global; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `_.indexOf` without support for binary searches + * or `fromIndex` constraints. + * + * @private + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value or `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + var index = (fromIndex || 0) - 1, + length = array ? array.length : 0; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * An implementation of `_.contains` for cache objects that mimics the return + * signature of `_.indexOf` by returning `0` if the value is found, else `-1`. + * + * @private + * @param {Object} cache The cache object to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns `0` if `value` is found, else `-1`. + */ + function cacheIndexOf(cache, value) { + var type = typeof value; + cache = cache.cache; + + if (type == 'boolean' || value == null) { + return cache[value] ? 0 : -1; + } + if (type != 'number' && type != 'string') { + type = 'object'; + } + var key = type == 'number' ? value : keyPrefix + value; + cache = (cache = cache[type]) && cache[key]; + + return type == 'object' + ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1) + : (cache ? 0 : -1); + } + + /** + * Adds a given value to the corresponding cache object. + * + * @private + * @param {*} value The value to add to the cache. + */ + function cachePush(value) { + var cache = this.cache, + type = typeof value; + + if (type == 'boolean' || value == null) { + cache[value] = true; + } else { + if (type != 'number' && type != 'string') { + type = 'object'; + } + var key = type == 'number' ? value : keyPrefix + value, + typeCache = cache[type] || (cache[type] = {}); + + if (type == 'object') { + (typeCache[key] || (typeCache[key] = [])).push(value); + } else { + typeCache[key] = true; + } + } + } + + /** + * Used by `_.max` and `_.min` as the default callback when a given + * collection is a string value. + * + * @private + * @param {string} value The character to inspect. + * @returns {number} Returns the code unit of given character. + */ + function charAtCallback(value) { + return value.charCodeAt(0); + } + + /** + * Used by `sortBy` to compare transformed `collection` elements, stable sorting + * them in ascending order. + * + * @private + * @param {Object} a The object to compare to `b`. + * @param {Object} b The object to compare to `a`. + * @returns {number} Returns the sort order indicator of `1` or `-1`. + */ + function compareAscending(a, b) { + var ac = a.criteria, + bc = b.criteria, + index = -1, + length = ac.length; + + while (++index < length) { + var value = ac[index], + other = bc[index]; + + if (value !== other) { + if (value > other || typeof value == 'undefined') { + return 1; + } + if (value < other || typeof other == 'undefined') { + return -1; + } + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to return the same value for + // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247 + // + // This also ensures a stable sort in V8 and other engines. + // See http://code.google.com/p/v8/issues/detail?id=90 + return a.index - b.index; + } + + /** + * Creates a cache object to optimize linear searches of large arrays. + * + * @private + * @param {Array} [array=[]] The array to search. + * @returns {null|Object} Returns the cache object or `null` if caching should not be used. + */ + function createCache(array) { + var index = -1, + length = array.length, + first = array[0], + mid = array[(length / 2) | 0], + last = array[length - 1]; + + if (first && typeof first == 'object' && + mid && typeof mid == 'object' && last && typeof last == 'object') { + return false; + } + var cache = getObject(); + cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false; + + var result = getObject(); + result.array = array; + result.cache = cache; + result.push = cachePush; + + while (++index < length) { + result.push(array[index]); + } + return result; + } + + /** + * Used by `template` to escape characters for inclusion in compiled + * string literals. + * + * @private + * @param {string} match The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(match) { + return '\\' + stringEscapes[match]; + } + + /** + * Gets an array from the array pool or creates a new one if the pool is empty. + * + * @private + * @returns {Array} The array from the pool. + */ + function getArray() { + return arrayPool.pop() || []; + } + + /** + * Gets an object from the object pool or creates a new one if the pool is empty. + * + * @private + * @returns {Object} The object from the pool. + */ + function getObject() { + return objectPool.pop() || { + 'array': null, + 'cache': null, + 'criteria': null, + 'false': false, + 'index': 0, + 'null': false, + 'number': null, + 'object': null, + 'push': null, + 'string': null, + 'true': false, + 'undefined': false, + 'value': null + }; + } + + /** + * Releases the given array back to the array pool. + * + * @private + * @param {Array} [array] The array to release. + */ + function releaseArray(array) { + array.length = 0; + if (arrayPool.length < maxPoolSize) { + arrayPool.push(array); + } + } + + /** + * Releases the given object back to the object pool. + * + * @private + * @param {Object} [object] The object to release. + */ + function releaseObject(object) { + var cache = object.cache; + if (cache) { + releaseObject(cache); + } + object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; + if (objectPool.length < maxPoolSize) { + objectPool.push(object); + } + } + + /** + * Slices the `collection` from the `start` index up to, but not including, + * the `end` index. + * + * Note: This function is used instead of `Array#slice` to support node lists + * in IE < 9 and to ensure dense arrays are returned. + * + * @private + * @param {Array|Object|string} collection The collection to slice. + * @param {number} start The start index. + * @param {number} end The end index. + * @returns {Array} Returns the new array. + */ + function slice(array, start, end) { + start || (start = 0); + if (typeof end == 'undefined') { + end = array ? array.length : 0; + } + var index = -1, + length = end - start || 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = array[start + index]; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new `lodash` function using the given context object. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} [context=root] The context object. + * @returns {Function} Returns the `lodash` function. + */ + function runInContext(context) { + // Avoid issues with some ES3 environments that attempt to use values, named + // after built-in constructors like `Object`, for the creation of literals. + // ES5 clears this up by stating that literals must use built-in constructors. + // See http://es5.github.io/#x11.1.5. + context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; + + /** Native constructor references */ + var Array = context.Array, + Boolean = context.Boolean, + Date = context.Date, + Function = context.Function, + Math = context.Math, + Number = context.Number, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** + * Used for `Array` method references. + * + * Normally `Array.prototype` would suffice, however, using an array literal + * avoids issues in Narwhal. + */ + var arrayRef = []; + + /** Used for native method references */ + var objectProto = Object.prototype; + + /** Used to restore the original `_` reference in `noConflict` */ + var oldDash = context._; + + /** Used to resolve the internal [[Class]] of values */ + var toString = objectProto.toString; + + /** Used to detect if a method is native */ + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + /** Native method shortcuts */ + var ceil = Math.ceil, + clearTimeout = context.clearTimeout, + floor = Math.floor, + fnToString = Function.prototype.toString, + getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, + hasOwnProperty = objectProto.hasOwnProperty, + push = arrayRef.push, + setTimeout = context.setTimeout, + splice = arrayRef.splice, + unshift = arrayRef.unshift; + + /** Used to set meta data on functions */ + var defineProperty = (function() { + // IE 8 only accepts DOM elements + try { + var o = {}, + func = isNative(func = Object.defineProperty) && func, + result = func(o, o, o) && func; + } catch(e) { } + return result; + }()); + + /* Native method shortcuts for methods with the same name as other `lodash` methods */ + var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, + nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, + nativeIsFinite = context.isFinite, + nativeIsNaN = context.isNaN, + nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, + nativeMax = Math.max, + nativeMin = Math.min, + nativeParseInt = context.parseInt, + nativeRandom = Math.random; + + /** Used to lookup a built-in constructor by [[Class]] */ + var ctorByClass = {}; + ctorByClass[arrayClass] = Array; + ctorByClass[boolClass] = Boolean; + ctorByClass[dateClass] = Date; + ctorByClass[funcClass] = Function; + ctorByClass[objectClass] = Object; + ctorByClass[numberClass] = Number; + ctorByClass[regexpClass] = RegExp; + ctorByClass[stringClass] = String; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps the given value to enable intuitive + * method chaining. + * + * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, + * and `unshift` + * + * Chaining is supported in custom builds as long as the `value` method is + * implicitly or explicitly included in the build. + * + * The chainable wrapper functions are: + * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, + * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, + * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, + * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, + * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, + * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, + * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, + * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, + * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, + * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, + * and `zip` + * + * The non-chainable wrapper functions are: + * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, + * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, + * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, + * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, + * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, + * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, + * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, + * `template`, `unescape`, `uniqueId`, and `value` + * + * The wrapper functions `first` and `last` return wrapped values when `n` is + * provided, otherwise they return unwrapped values. + * + * Explicit chaining can be enabled by using the `_.chain` method. + * + * @name _ + * @constructor + * @category Chaining + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns a `lodash` instance. + * @example + * + * var wrapped = _([1, 2, 3]); + * + * // returns an unwrapped value + * wrapped.reduce(function(sum, num) { + * return sum + num; + * }); + * // => 6 + * + * // returns a wrapped value + * var squares = wrapped.map(function(num) { + * return num * num; + * }); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor + return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) + ? value + : new lodashWrapper(value); + } + + /** + * A fast path for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap in a `lodash` instance. + * @param {boolean} chainAll A flag to enable chaining for all methods + * @returns {Object} Returns a `lodash` instance. + */ + function lodashWrapper(value, chainAll) { + this.__chain__ = !!chainAll; + this.__wrapped__ = value; + } + // ensure `new lodashWrapper` is an instance of `lodash` + lodashWrapper.prototype = lodash.prototype; + + /** + * An object used to flag environments features. + * + * @static + * @memberOf _ + * @type Object + */ + var support = lodash.support = {}; + + /** + * Detect if functions can be decompiled by `Function#toString` + * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). + * + * @memberOf _.support + * @type boolean + */ + support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext); + + /** + * Detect if `Function#name` is supported (all but IE). + * + * @memberOf _.support + * @type boolean + */ + support.funcNames = typeof Function.name == 'string'; + + /** + * By default, the template delimiters used by Lo-Dash are similar to those in + * embedded Ruby (ERB). Change the following template settings to use alternative + * delimiters. + * + * @static + * @memberOf _ + * @type Object + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'escape': /<%-([\s\S]+?)%>/g, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'evaluate': /<%([\s\S]+?)%>/g, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type string + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type Object + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type Function + */ + '_': lodash + } + }; + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `_.bind` that creates the bound function and + * sets its meta data. + * + * @private + * @param {Array} bindData The bind data array. + * @returns {Function} Returns the new bound function. + */ + function baseBind(bindData) { + var func = bindData[0], + partialArgs = bindData[2], + thisArg = bindData[4]; + + function bound() { + // `Function#bind` spec + // http://es5.github.io/#x15.3.4.5 + if (partialArgs) { + // avoid `arguments` object deoptimizations by using `slice` instead + // of `Array.prototype.slice.call` and not assigning `arguments` to a + // variable as a ternary expression + var args = slice(partialArgs); + push.apply(args, arguments); + } + // mimic the constructor's `return` behavior + // http://es5.github.io/#x13.2.2 + if (this instanceof bound) { + // ensure `new bound` is an instance of `func` + var thisBinding = baseCreate(func.prototype), + result = func.apply(thisBinding, args || arguments); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisArg, args || arguments); + } + setBindData(bound, bindData); + return bound; + } + + /** + * The base implementation of `_.clone` without argument juggling or support + * for `thisArg` binding. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep=false] Specify a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates clones with source counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, isDeep, callback, stackA, stackB) { + if (callback) { + var result = callback(value); + if (typeof result != 'undefined') { + return result; + } + } + // inspect [[Class]] + var isObj = isObject(value); + if (isObj) { + var className = toString.call(value); + if (!cloneableClasses[className]) { + return value; + } + var ctor = ctorByClass[className]; + switch (className) { + case boolClass: + case dateClass: + return new ctor(+value); + + case numberClass: + case stringClass: + return new ctor(value); + + case regexpClass: + result = ctor(value.source, reFlags.exec(value)); + result.lastIndex = value.lastIndex; + return result; + } + } else { + return value; + } + var isArr = isArray(value); + if (isDeep) { + // check for circular references and return corresponding clone + var initedStack = !stackA; + stackA || (stackA = getArray()); + stackB || (stackB = getArray()); + + var length = stackA.length; + while (length--) { + if (stackA[length] == value) { + return stackB[length]; + } + } + result = isArr ? ctor(value.length) : {}; + } + else { + result = isArr ? slice(value) : assign({}, value); + } + // add array properties assigned by `RegExp#exec` + if (isArr) { + if (hasOwnProperty.call(value, 'index')) { + result.index = value.index; + } + if (hasOwnProperty.call(value, 'input')) { + result.input = value.input; + } + } + // exit for shallow clone + if (!isDeep) { + return result; + } + // add the source value to the stack of traversed objects + // and associate it with its clone + stackA.push(value); + stackB.push(result); + + // recursively populate clone (susceptible to call stack limits) + (isArr ? forEach : forOwn)(value, function(objValue, key) { + result[key] = baseClone(objValue, isDeep, callback, stackA, stackB); + }); + + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } + return result; + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + function baseCreate(prototype, properties) { + return isObject(prototype) ? nativeCreate(prototype) : {}; + } + // fallback for browsers without `Object.create` + if (!nativeCreate) { + baseCreate = (function() { + function Object() {} + return function(prototype) { + if (isObject(prototype)) { + Object.prototype = prototype; + var result = new Object; + Object.prototype = null; + } + return result || context.Object(); + }; + }()); + } + + /** + * The base implementation of `_.createCallback` without support for creating + * "_.pluck" or "_.where" style callbacks. + * + * @private + * @param {*} [func=identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of the created callback. + * @param {number} [argCount] The number of arguments the callback accepts. + * @returns {Function} Returns a callback function. + */ + function baseCreateCallback(func, thisArg, argCount) { + if (typeof func != 'function') { + return identity; + } + // exit early for no `thisArg` or already bound by `Function#bind` + if (typeof thisArg == 'undefined' || !('prototype' in func)) { + return func; + } + var bindData = func.__bindData__; + if (typeof bindData == 'undefined') { + if (support.funcNames) { + bindData = !func.name; + } + bindData = bindData || !support.funcDecomp; + if (!bindData) { + var source = fnToString.call(func); + if (!support.funcNames) { + bindData = !reFuncName.test(source); + } + if (!bindData) { + // checks if `func` references the `this` keyword and stores the result + bindData = reThis.test(source); + setBindData(func, bindData); + } + } + } + // exit early if there are no `this` references or `func` is bound + if (bindData === false || (bindData !== true && bindData[1] & 1)) { + return func; + } + switch (argCount) { + case 1: return function(value) { + return func.call(thisArg, value); + }; + case 2: return function(a, b) { + return func.call(thisArg, a, b); + }; + case 3: return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(thisArg, accumulator, value, index, collection); + }; + } + return bind(func, thisArg); + } + + /** + * The base implementation of `createWrapper` that creates the wrapper and + * sets its meta data. + * + * @private + * @param {Array} bindData The bind data array. + * @returns {Function} Returns the new function. + */ + function baseCreateWrapper(bindData) { + var func = bindData[0], + bitmask = bindData[1], + partialArgs = bindData[2], + partialRightArgs = bindData[3], + thisArg = bindData[4], + arity = bindData[5]; + + var isBind = bitmask & 1, + isBindKey = bitmask & 2, + isCurry = bitmask & 4, + isCurryBound = bitmask & 8, + key = func; + + function bound() { + var thisBinding = isBind ? thisArg : this; + if (partialArgs) { + var args = slice(partialArgs); + push.apply(args, arguments); + } + if (partialRightArgs || isCurry) { + args || (args = slice(arguments)); + if (partialRightArgs) { + push.apply(args, partialRightArgs); + } + if (isCurry && args.length < arity) { + bitmask |= 16 & ~32; + return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); + } + } + args || (args = arguments); + if (isBindKey) { + func = thisBinding[key]; + } + if (this instanceof bound) { + thisBinding = baseCreate(func.prototype); + var result = func.apply(thisBinding, args); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisBinding, args); + } + setBindData(bound, bindData); + return bound; + } + + /** + * The base implementation of `_.difference` that accepts a single array + * of values to exclude. + * + * @private + * @param {Array} array The array to process. + * @param {Array} [values] The array of values to exclude. + * @returns {Array} Returns a new array of filtered values. + */ + function baseDifference(array, values) { + var index = -1, + indexOf = getIndexOf(), + length = array ? array.length : 0, + isLarge = length >= largeArraySize && indexOf === baseIndexOf, + result = []; + + if (isLarge) { + var cache = createCache(values); + if (cache) { + indexOf = cacheIndexOf; + values = cache; + } else { + isLarge = false; + } + } + while (++index < length) { + var value = array[index]; + if (indexOf(values, value) < 0) { + result.push(value); + } + } + if (isLarge) { + releaseObject(values); + } + return result; + } + + /** + * The base implementation of `_.flatten` without support for callback + * shorthands or `thisArg` binding. + * + * @private + * @param {Array} array The array to flatten. + * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. + * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects. + * @param {number} [fromIndex=0] The index to start from. + * @returns {Array} Returns a new flattened array. + */ + function baseFlatten(array, isShallow, isStrict, fromIndex) { + var index = (fromIndex || 0) - 1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + + if (value && typeof value == 'object' && typeof value.length == 'number' + && (isArray(value) || isArguments(value))) { + // recursively flatten arrays (susceptible to call stack limits) + if (!isShallow) { + value = baseFlatten(value, isShallow, isStrict); + } + var valIndex = -1, + valLength = value.length, + resIndex = result.length; + + result.length += valLength; + while (++valIndex < valLength) { + result[resIndex++] = value[valIndex]; + } + } else if (!isStrict) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.isEqual`, without support for `thisArg` binding, + * that allows partial "_.where" style comparisons. + * + * @private + * @param {*} a The value to compare. + * @param {*} b The other value to compare. + * @param {Function} [callback] The function to customize comparing values. + * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons. + * @param {Array} [stackA=[]] Tracks traversed `a` objects. + * @param {Array} [stackB=[]] Tracks traversed `b` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(a, b, callback, isWhere, stackA, stackB) { + // used to indicate that when comparing objects, `a` has at least the properties of `b` + if (callback) { + var result = callback(a, b); + if (typeof result != 'undefined') { + return !!result; + } + } + // exit early for identical values + if (a === b) { + // treat `+0` vs. `-0` as not equal + return a !== 0 || (1 / a == 1 / b); + } + var type = typeof a, + otherType = typeof b; + + // exit early for unlike primitive values + if (a === a && + !(a && objectTypes[type]) && + !(b && objectTypes[otherType])) { + return false; + } + // exit early for `null` and `undefined` avoiding ES3's Function#call behavior + // http://es5.github.io/#x15.3.4.4 + if (a == null || b == null) { + return a === b; + } + // compare [[Class]] names + var className = toString.call(a), + otherClass = toString.call(b); + + if (className == argsClass) { + className = objectClass; + } + if (otherClass == argsClass) { + otherClass = objectClass; + } + if (className != otherClass) { + return false; + } + switch (className) { + case boolClass: + case dateClass: + // coerce dates and booleans to numbers, dates to milliseconds and booleans + // to `1` or `0` treating invalid dates coerced to `NaN` as not equal + return +a == +b; + + case numberClass: + // treat `NaN` vs. `NaN` as equal + return (a != +a) + ? b != +b + // but treat `+0` vs. `-0` as not equal + : (a == 0 ? (1 / a == 1 / b) : a == +b); + + case regexpClass: + case stringClass: + // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) + // treat string primitives and their corresponding object instances as equal + return a == String(b); + } + var isArr = className == arrayClass; + if (!isArr) { + // unwrap any `lodash` wrapped values + var aWrapped = hasOwnProperty.call(a, '__wrapped__'), + bWrapped = hasOwnProperty.call(b, '__wrapped__'); + + if (aWrapped || bWrapped) { + return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB); + } + // exit for functions and DOM nodes + if (className != objectClass) { + return false; + } + // in older versions of Opera, `arguments` objects have `Array` constructors + var ctorA = a.constructor, + ctorB = b.constructor; + + // non `Object` object instances with different constructors are not equal + if (ctorA != ctorB && + !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && + ('constructor' in a && 'constructor' in b) + ) { + return false; + } + } + // assume cyclic structures are equal + // the algorithm for detecting cyclic structures is adapted from ES 5.1 + // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) + var initedStack = !stackA; + stackA || (stackA = getArray()); + stackB || (stackB = getArray()); + + var length = stackA.length; + while (length--) { + if (stackA[length] == a) { + return stackB[length] == b; + } + } + var size = 0; + result = true; + + // add `a` and `b` to the stack of traversed objects + stackA.push(a); + stackB.push(b); + + // recursively compare objects and arrays (susceptible to call stack limits) + if (isArr) { + // compare lengths to determine if a deep comparison is necessary + length = a.length; + size = b.length; + result = size == length; + + if (result || isWhere) { + // deep compare the contents, ignoring non-numeric properties + while (size--) { + var index = length, + value = b[size]; + + if (isWhere) { + while (index--) { + if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) { + break; + } + } + } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) { + break; + } + } + } + } + else { + // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` + // which, in this case, is more costly + forIn(b, function(value, key, b) { + if (hasOwnProperty.call(b, key)) { + // count the number of properties. + size++; + // deep compare each property value. + return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB)); + } + }); + + if (result && !isWhere) { + // ensure both objects have the same number of properties + forIn(a, function(value, key, a) { + if (hasOwnProperty.call(a, key)) { + // `size` will be `-1` if `a` has more properties than `b` + return (result = --size > -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } + return result; + } + + /** + * The base implementation of `_.merge` without argument juggling or support + * for `thisArg` binding. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} [callback] The function to customize merging properties. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates values with source counterparts. + */ + function baseMerge(object, source, callback, stackA, stackB) { + (isArray(source) ? forEach : forOwn)(source, function(source, key) { + var found, + isArr, + result = source, + value = object[key]; + + if (source && ((isArr = isArray(source)) || isPlainObject(source))) { + // avoid merging previously merged cyclic sources + var stackLength = stackA.length; + while (stackLength--) { + if ((found = stackA[stackLength] == source)) { + value = stackB[stackLength]; + break; + } + } + if (!found) { + var isShallow; + if (callback) { + result = callback(value, source); + if ((isShallow = typeof result != 'undefined')) { + value = result; + } + } + if (!isShallow) { + value = isArr + ? (isArray(value) ? value : []) + : (isPlainObject(value) ? value : {}); + } + // add `source` and associated `value` to the stack of traversed objects + stackA.push(source); + stackB.push(value); + + // recursively merge objects and arrays (susceptible to call stack limits) + if (!isShallow) { + baseMerge(value, source, callback, stackA, stackB); + } + } + } + else { + if (callback) { + result = callback(value, source); + if (typeof result == 'undefined') { + result = source; + } + } + if (typeof result != 'undefined') { + value = result; + } + } + object[key] = value; + }); + } + + /** + * The base implementation of `_.random` without argument juggling or support + * for returning floating-point numbers. + * + * @private + * @param {number} min The minimum possible value. + * @param {number} max The maximum possible value. + * @returns {number} Returns a random number. + */ + function baseRandom(min, max) { + return min + floor(nativeRandom() * (max - min + 1)); + } + + /** + * The base implementation of `_.uniq` without support for callback shorthands + * or `thisArg` binding. + * + * @private + * @param {Array} array The array to process. + * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. + * @param {Function} [callback] The function called per iteration. + * @returns {Array} Returns a duplicate-value-free array. + */ + function baseUniq(array, isSorted, callback) { + var index = -1, + indexOf = getIndexOf(), + length = array ? array.length : 0, + result = []; + + var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf, + seen = (callback || isLarge) ? getArray() : result; + + if (isLarge) { + var cache = createCache(seen); + indexOf = cacheIndexOf; + seen = cache; + } + while (++index < length) { + var value = array[index], + computed = callback ? callback(value, index, array) : value; + + if (isSorted + ? !index || seen[seen.length - 1] !== computed + : indexOf(seen, computed) < 0 + ) { + if (callback || isLarge) { + seen.push(computed); + } + result.push(value); + } + } + if (isLarge) { + releaseArray(seen.array); + releaseObject(seen); + } else if (callback) { + releaseArray(seen); + } + return result; + } + + /** + * Creates a function that aggregates a collection, creating an object composed + * of keys generated from the results of running each element of the collection + * through a callback. The given `setter` function sets the keys and values + * of the composed object. + * + * @private + * @param {Function} setter The setter function. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter) { + return function(collection, callback, thisArg) { + var result = {}; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + setter(result, value, callback(value, index, collection), collection); + } + } else { + forOwn(collection, function(value, key, collection) { + setter(result, value, callback(value, key, collection), collection); + }); + } + return result; + }; + } + + /** + * Creates a function that, when called, either curries or invokes `func` + * with an optional `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to reference. + * @param {number} bitmask The bitmask of method flags to compose. + * The bitmask may be composed of the following flags: + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` + * 8 - `_.curry` (bound) + * 16 - `_.partial` + * 32 - `_.partialRight` + * @param {Array} [partialArgs] An array of arguments to prepend to those + * provided to the new function. + * @param {Array} [partialRightArgs] An array of arguments to append to those + * provided to the new function. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new function. + */ + function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { + var isBind = bitmask & 1, + isBindKey = bitmask & 2, + isCurry = bitmask & 4, + isCurryBound = bitmask & 8, + isPartial = bitmask & 16, + isPartialRight = bitmask & 32; + + if (!isBindKey && !isFunction(func)) { + throw new TypeError; + } + if (isPartial && !partialArgs.length) { + bitmask &= ~16; + isPartial = partialArgs = false; + } + if (isPartialRight && !partialRightArgs.length) { + bitmask &= ~32; + isPartialRight = partialRightArgs = false; + } + var bindData = func && func.__bindData__; + if (bindData && bindData !== true) { + // clone `bindData` + bindData = slice(bindData); + if (bindData[2]) { + bindData[2] = slice(bindData[2]); + } + if (bindData[3]) { + bindData[3] = slice(bindData[3]); + } + // set `thisBinding` is not previously bound + if (isBind && !(bindData[1] & 1)) { + bindData[4] = thisArg; + } + // set if previously bound but not currently (subsequent curried functions) + if (!isBind && bindData[1] & 1) { + bitmask |= 8; + } + // set curried arity if not yet set + if (isCurry && !(bindData[1] & 4)) { + bindData[5] = arity; + } + // append partial left arguments + if (isPartial) { + push.apply(bindData[2] || (bindData[2] = []), partialArgs); + } + // append partial right arguments + if (isPartialRight) { + unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); + } + // merge flags + bindData[1] |= bitmask; + return createWrapper.apply(null, bindData); + } + // fast path for `_.bind` + var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; + return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); + } + + /** + * Used by `escape` to convert characters to HTML entities. + * + * @private + * @param {string} match The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeHtmlChar(match) { + return htmlEscapes[match]; + } + + /** + * Gets the appropriate "indexOf" function. If the `_.indexOf` method is + * customized, this method returns the custom method, otherwise it returns + * the `baseIndexOf` function. + * + * @private + * @returns {Function} Returns the "indexOf" function. + */ + function getIndexOf() { + var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result; + return result; + } + + /** + * Checks if `value` is a native function. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. + */ + function isNative(value) { + return typeof value == 'function' && reNative.test(value); + } + + /** + * Sets `this` binding data on a given function. + * + * @private + * @param {Function} func The function to set data on. + * @param {Array} value The data array to set. + */ + var setBindData = !defineProperty ? noop : function(func, value) { + descriptor.value = value; + defineProperty(func, '__bindData__', descriptor); + }; + + /** + * A fallback implementation of `isPlainObject` which checks if a given value + * is an object created by the `Object` constructor, assuming objects created + * by the `Object` constructor have no inherited enumerable properties and that + * there are no `Object.prototype` extensions. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + */ + function shimIsPlainObject(value) { + var ctor, + result; + + // avoid non Object objects, `arguments` objects, and DOM elements + if (!(value && toString.call(value) == objectClass) || + (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) { + return false; + } + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + forIn(value, function(value, key) { + result = key; + }); + return typeof result == 'undefined' || hasOwnProperty.call(value, result); + } + + /** + * Used by `unescape` to convert HTML entities to characters. + * + * @private + * @param {string} match The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + function unescapeHtmlChar(match) { + return htmlUnescapes[match]; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Checks if `value` is an `arguments` object. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. + * @example + * + * (function() { return _.isArguments(arguments); })(1, 2, 3); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + toString.call(value) == argsClass || false; + } + + /** + * Checks if `value` is an array. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an array, else `false`. + * @example + * + * (function() { return _.isArray(arguments); })(); + * // => false + * + * _.isArray([1, 2, 3]); + * // => true + */ + var isArray = nativeIsArray || function(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + toString.call(value) == arrayClass || false; + }; + + /** + * A fallback implementation of `Object.keys` which produces an array of the + * given object's own enumerable property names. + * + * @private + * @type Function + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names. + */ + var shimKeys = function(object) { + var index, iterable = object, result = []; + if (!iterable) return result; + if (!(objectTypes[typeof object])) return result; + for (index in iterable) { + if (hasOwnProperty.call(iterable, index)) { + result.push(index); + } + } + return result + }; + + /** + * Creates an array composed of the own enumerable property names of an object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names. + * @example + * + * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); + * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) + */ + var keys = !nativeKeys ? shimKeys : function(object) { + if (!isObject(object)) { + return []; + } + return nativeKeys(object); + }; + + /** + * Used to convert characters to HTML entities: + * + * Though the `>` character is escaped for symmetry, characters like `>` and `/` + * don't require escaping in HTML and have no special meaning unless they're part + * of a tag or an unquoted attribute value. + * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") + */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to convert HTML entities to characters */ + var htmlUnescapes = invert(htmlEscapes); + + /** Used to match HTML entities and HTML characters */ + var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'), + reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g'); + + /*--------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object. Subsequent sources will overwrite property assignments of previous + * sources. If a callback is provided it will be executed to produce the + * assigned values. The callback is bound to `thisArg` and invoked with two + * arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @type Function + * @alias extend + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param {Function} [callback] The function to customize assigning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); + * // => { 'name': 'fred', 'employer': 'slate' } + * + * var defaults = _.partialRight(_.assign, function(a, b) { + * return typeof a == 'undefined' ? b : a; + * }); + * + * var object = { 'name': 'barney' }; + * defaults(object, { 'name': 'fred', 'employer': 'slate' }); + * // => { 'name': 'barney', 'employer': 'slate' } + */ + var assign = function(object, source, guard) { + var index, iterable = object, result = iterable; + if (!iterable) return result; + var args = arguments, + argsIndex = 0, + argsLength = typeof guard == 'number' ? 2 : args.length; + if (argsLength > 3 && typeof args[argsLength - 2] == 'function') { + var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2); + } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') { + callback = args[--argsLength]; + } + while (++argsIndex < argsLength) { + iterable = args[argsIndex]; + if (iterable && objectTypes[typeof iterable]) { + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]; + } + } + } + return result + }; + + /** + * Creates a clone of `value`. If `isDeep` is `true` nested objects will also + * be cloned, otherwise they will be assigned by reference. If a callback + * is provided it will be executed to produce the cloned values. If the + * callback returns `undefined` cloning will be handled by the method instead. + * The callback is bound to `thisArg` and invoked with one argument; (value). + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to clone. + * @param {boolean} [isDeep=false] Specify a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the cloned value. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * var shallow = _.clone(characters); + * shallow[0] === characters[0]; + * // => true + * + * var deep = _.clone(characters, true); + * deep[0] === characters[0]; + * // => false + * + * _.mixin({ + * 'clone': _.partialRight(_.clone, function(value) { + * return _.isElement(value) ? value.cloneNode(false) : undefined; + * }) + * }); + * + * var clone = _.clone(document.body); + * clone.childNodes.length; + * // => 0 + */ + function clone(value, isDeep, callback, thisArg) { + // allows working with "Collections" methods without using their `index` + // and `collection` arguments for `isDeep` and `callback` + if (typeof isDeep != 'boolean' && isDeep != null) { + thisArg = callback; + callback = isDeep; + isDeep = false; + } + return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); + } + + /** + * Creates a deep clone of `value`. If a callback is provided it will be + * executed to produce the cloned values. If the callback returns `undefined` + * cloning will be handled by the method instead. The callback is bound to + * `thisArg` and invoked with one argument; (value). + * + * Note: This method is loosely based on the structured clone algorithm. Functions + * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and + * objects created by constructors other than `Object` are cloned to plain `Object` objects. + * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the deep cloned value. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * var deep = _.cloneDeep(characters); + * deep[0] === characters[0]; + * // => false + * + * var view = { + * 'label': 'docs', + * 'node': element + * }; + * + * var clone = _.cloneDeep(view, function(value) { + * return _.isElement(value) ? value.cloneNode(true) : undefined; + * }); + * + * clone.node == view.node; + * // => false + */ + function cloneDeep(value, callback, thisArg) { + return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); + } + + /** + * Creates an object that inherits from the given `prototype` object. If a + * `properties` object is provided its own enumerable properties are assigned + * to the created object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties ? assign(result, properties) : result; + } + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object for all destination properties that resolve to `undefined`. Once a + * property is set, additional defaults of the same property will be ignored. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param- {Object} [guard] Allows working with `_.reduce` without using its + * `key` and `object` arguments as sources. + * @returns {Object} Returns the destination object. + * @example + * + * var object = { 'name': 'barney' }; + * _.defaults(object, { 'name': 'fred', 'employer': 'slate' }); + * // => { 'name': 'barney', 'employer': 'slate' } + */ + var defaults = function(object, source, guard) { + var index, iterable = object, result = iterable; + if (!iterable) return result; + var args = arguments, + argsIndex = 0, + argsLength = typeof guard == 'number' ? 2 : args.length; + while (++argsIndex < argsLength) { + iterable = args[argsIndex]; + if (iterable && objectTypes[typeof iterable]) { + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + if (typeof result[index] == 'undefined') result[index] = iterable[index]; + } + } + } + return result + }; + + /** + * This method is like `_.findIndex` except that it returns the key of the + * first element that passes the callback check, instead of the element itself. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to search. + * @param {Function|Object|string} [callback=identity] The function called per + * iteration. If a property name or object is provided it will be used to + * create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {string|undefined} Returns the key of the found element, else `undefined`. + * @example + * + * var characters = { + * 'barney': { 'age': 36, 'blocked': false }, + * 'fred': { 'age': 40, 'blocked': true }, + * 'pebbles': { 'age': 1, 'blocked': false } + * }; + * + * _.findKey(characters, function(chr) { + * return chr.age < 40; + * }); + * // => 'barney' (property order is not guaranteed across environments) + * + * // using "_.where" callback shorthand + * _.findKey(characters, { 'age': 1 }); + * // => 'pebbles' + * + * // using "_.pluck" callback shorthand + * _.findKey(characters, 'blocked'); + * // => 'fred' + */ + function findKey(object, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forOwn(object, function(value, key, object) { + if (callback(value, key, object)) { + result = key; + return false; + } + }); + return result; + } + + /** + * This method is like `_.findKey` except that it iterates over elements + * of a `collection` in the opposite order. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to search. + * @param {Function|Object|string} [callback=identity] The function called per + * iteration. If a property name or object is provided it will be used to + * create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {string|undefined} Returns the key of the found element, else `undefined`. + * @example + * + * var characters = { + * 'barney': { 'age': 36, 'blocked': true }, + * 'fred': { 'age': 40, 'blocked': false }, + * 'pebbles': { 'age': 1, 'blocked': true } + * }; + * + * _.findLastKey(characters, function(chr) { + * return chr.age < 40; + * }); + * // => returns `pebbles`, assuming `_.findKey` returns `barney` + * + * // using "_.where" callback shorthand + * _.findLastKey(characters, { 'age': 40 }); + * // => 'fred' + * + * // using "_.pluck" callback shorthand + * _.findLastKey(characters, 'blocked'); + * // => 'pebbles' + */ + function findLastKey(object, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forOwnRight(object, function(value, key, object) { + if (callback(value, key, object)) { + result = key; + return false; + } + }); + return result; + } + + /** + * Iterates over own and inherited enumerable properties of an object, + * executing the callback for each property. The callback is bound to `thisArg` + * and invoked with three arguments; (value, key, object). Callbacks may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * Shape.prototype.move = function(x, y) { + * this.x += x; + * this.y += y; + * }; + * + * _.forIn(new Shape, function(value, key) { + * console.log(key); + * }); + * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) + */ + var forIn = function(collection, callback, thisArg) { + var index, iterable = collection, result = iterable; + if (!iterable) return result; + if (!objectTypes[typeof iterable]) return result; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + for (index in iterable) { + if (callback(iterable[index], index, collection) === false) return result; + } + return result + }; + + /** + * This method is like `_.forIn` except that it iterates over elements + * of a `collection` in the opposite order. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * Shape.prototype.move = function(x, y) { + * this.x += x; + * this.y += y; + * }; + * + * _.forInRight(new Shape, function(value, key) { + * console.log(key); + * }); + * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move' + */ + function forInRight(object, callback, thisArg) { + var pairs = []; + + forIn(object, function(value, key) { + pairs.push(key, value); + }); + + var length = pairs.length; + callback = baseCreateCallback(callback, thisArg, 3); + while (length--) { + if (callback(pairs[length--], pairs[length], object) === false) { + break; + } + } + return object; + } + + /** + * Iterates over own enumerable properties of an object, executing the callback + * for each property. The callback is bound to `thisArg` and invoked with three + * arguments; (value, key, object). Callbacks may exit iteration early by + * explicitly returning `false`. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * console.log(key); + * }); + * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) + */ + var forOwn = function(collection, callback, thisArg) { + var index, iterable = collection, result = iterable; + if (!iterable) return result; + if (!objectTypes[typeof iterable]) return result; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + if (callback(iterable[index], index, collection) === false) return result; + } + return result + }; + + /** + * This method is like `_.forOwn` except that it iterates over elements + * of a `collection` in the opposite order. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * console.log(key); + * }); + * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length' + */ + function forOwnRight(object, callback, thisArg) { + var props = keys(object), + length = props.length; + + callback = baseCreateCallback(callback, thisArg, 3); + while (length--) { + var key = props[length]; + if (callback(object[key], key, object) === false) { + break; + } + } + return object; + } + + /** + * Creates a sorted array of property names of all enumerable properties, + * own and inherited, of `object` that have function values. + * + * @static + * @memberOf _ + * @alias methods + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names that have function values. + * @example + * + * _.functions(_); + * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] + */ + function functions(object) { + var result = []; + forIn(object, function(value, key) { + if (isFunction(value)) { + result.push(key); + } + }); + return result.sort(); + } + + /** + * Checks if the specified property name exists as a direct property of `object`, + * instead of an inherited property. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @param {string} key The name of the property to check. + * @returns {boolean} Returns `true` if key is a direct property, else `false`. + * @example + * + * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); + * // => true + */ + function has(object, key) { + return object ? hasOwnProperty.call(object, key) : false; + } + + /** + * Creates an object composed of the inverted keys and values of the given object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to invert. + * @returns {Object} Returns the created inverted object. + * @example + * + * _.invert({ 'first': 'fred', 'second': 'barney' }); + * // => { 'fred': 'first', 'barney': 'second' } + */ + function invert(object) { + var index = -1, + props = keys(object), + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index]; + result[object[key]] = key; + } + return result; + } + + /** + * Checks if `value` is a boolean value. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`. + * @example + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + value && typeof value == 'object' && toString.call(value) == boolClass || false; + } + + /** + * Checks if `value` is a date. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a date, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + */ + function isDate(value) { + return value && typeof value == 'object' && toString.call(value) == dateClass || false; + } + + /** + * Checks if `value` is a DOM element. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + */ + function isElement(value) { + return value && value.nodeType === 1 || false; + } + + /** + * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a + * length of `0` and objects with no own enumerable properties are considered + * "empty". + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object|string} value The value to inspect. + * @returns {boolean} Returns `true` if the `value` is empty, else `false`. + * @example + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({}); + * // => true + * + * _.isEmpty(''); + * // => true + */ + function isEmpty(value) { + var result = true; + if (!value) { + return result; + } + var className = toString.call(value), + length = value.length; + + if ((className == arrayClass || className == stringClass || className == argsClass ) || + (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { + return !length; + } + forOwn(value, function() { + return (result = false); + }); + return result; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent to each other. If a callback is provided it will be executed + * to compare values. If the callback returns `undefined` comparisons will + * be handled by the method instead. The callback is bound to `thisArg` and + * invoked with two arguments; (a, b). + * + * @static + * @memberOf _ + * @category Objects + * @param {*} a The value to compare. + * @param {*} b The other value to compare. + * @param {Function} [callback] The function to customize comparing values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'name': 'fred' }; + * var copy = { 'name': 'fred' }; + * + * object == copy; + * // => false + * + * _.isEqual(object, copy); + * // => true + * + * var words = ['hello', 'goodbye']; + * var otherWords = ['hi', 'goodbye']; + * + * _.isEqual(words, otherWords, function(a, b) { + * var reGreet = /^(?:hello|hi)$/i, + * aGreet = _.isString(a) && reGreet.test(a), + * bGreet = _.isString(b) && reGreet.test(b); + * + * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; + * }); + * // => true + */ + function isEqual(a, b, callback, thisArg) { + return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2)); + } + + /** + * Checks if `value` is, or can be coerced to, a finite number. + * + * Note: This is not the same as native `isFinite` which will return true for + * booleans and empty strings. See http://es5.github.io/#x15.1.2.5. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is finite, else `false`. + * @example + * + * _.isFinite(-101); + * // => true + * + * _.isFinite('10'); + * // => true + * + * _.isFinite(true); + * // => false + * + * _.isFinite(''); + * // => false + * + * _.isFinite(Infinity); + * // => false + */ + function isFinite(value) { + return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); + } + + /** + * Checks if `value` is a function. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + */ + function isFunction(value) { + return typeof value == 'function'; + } + + /** + * Checks if `value` is the language type of Object. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(1); + * // => false + */ + function isObject(value) { + // check if the value is the ECMAScript language type of Object + // http://es5.github.io/#x8 + // and avoid a V8 bug + // http://code.google.com/p/v8/issues/detail?id=2291 + return !!(value && objectTypes[typeof value]); + } + + /** + * Checks if `value` is `NaN`. + * + * Note: This is not the same as native `isNaN` which will return `true` for + * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // `NaN` as a primitive is the only value that is not equal to itself + // (perform the [[Class]] check first to avoid errors with some host objects in IE) + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(undefined); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is a number. + * + * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a number, else `false`. + * @example + * + * _.isNumber(8.4 * 5); + * // => true + */ + function isNumber(value) { + return typeof value == 'number' || + value && typeof value == 'object' && toString.call(value) == numberClass || false; + } + + /** + * Checks if `value` is an object created by the `Object` constructor. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * _.isPlainObject(new Shape); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + */ + var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { + if (!(value && toString.call(value) == objectClass)) { + return false; + } + var valueOf = value.valueOf, + objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); + + return objProto + ? (value == objProto || getPrototypeOf(value) == objProto) + : shimIsPlainObject(value); + }; + + /** + * Checks if `value` is a regular expression. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`. + * @example + * + * _.isRegExp(/fred/); + * // => true + */ + function isRegExp(value) { + return value && typeof value == 'object' && toString.call(value) == regexpClass || false; + } + + /** + * Checks if `value` is a string. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a string, else `false`. + * @example + * + * _.isString('fred'); + * // => true + */ + function isString(value) { + return typeof value == 'string' || + value && typeof value == 'object' && toString.call(value) == stringClass || false; + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + */ + function isUndefined(value) { + return typeof value == 'undefined'; + } + + /** + * Creates an object with the same keys as `object` and values generated by + * running each own enumerable property of `object` through the callback. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new object with values of the results of each `callback` execution. + * @example + * + * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + * + * var characters = { + * 'fred': { 'name': 'fred', 'age': 40 }, + * 'pebbles': { 'name': 'pebbles', 'age': 1 } + * }; + * + * // using "_.pluck" callback shorthand + * _.mapValues(characters, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } + */ + function mapValues(object, callback, thisArg) { + var result = {}; + callback = lodash.createCallback(callback, thisArg, 3); + + forOwn(object, function(value, key, object) { + result[key] = callback(value, key, object); + }); + return result; + } + + /** + * Recursively merges own enumerable properties of the source object(s), that + * don't resolve to `undefined` into the destination object. Subsequent sources + * will overwrite property assignments of previous sources. If a callback is + * provided it will be executed to produce the merged values of the destination + * and source properties. If the callback returns `undefined` merging will + * be handled by the method instead. The callback is bound to `thisArg` and + * invoked with two arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param {Function} [callback] The function to customize merging properties. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * var names = { + * 'characters': [ + * { 'name': 'barney' }, + * { 'name': 'fred' } + * ] + * }; + * + * var ages = { + * 'characters': [ + * { 'age': 36 }, + * { 'age': 40 } + * ] + * }; + * + * _.merge(names, ages); + * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } + * + * var food = { + * 'fruits': ['apple'], + * 'vegetables': ['beet'] + * }; + * + * var otherFood = { + * 'fruits': ['banana'], + * 'vegetables': ['carrot'] + * }; + * + * _.merge(food, otherFood, function(a, b) { + * return _.isArray(a) ? a.concat(b) : undefined; + * }); + * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } + */ + function merge(object) { + var args = arguments, + length = 2; + + if (!isObject(object)) { + return object; + } + // allows working with `_.reduce` and `_.reduceRight` without using + // their `index` and `collection` arguments + if (typeof args[2] != 'number') { + length = args.length; + } + if (length > 3 && typeof args[length - 2] == 'function') { + var callback = baseCreateCallback(args[--length - 1], args[length--], 2); + } else if (length > 2 && typeof args[length - 1] == 'function') { + callback = args[--length]; + } + var sources = slice(arguments, 1, length), + index = -1, + stackA = getArray(), + stackB = getArray(); + + while (++index < length) { + baseMerge(object, sources[index], callback, stackA, stackB); + } + releaseArray(stackA); + releaseArray(stackB); + return object; + } + + /** + * Creates a shallow clone of `object` excluding the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If a callback is provided it will be executed for each + * property of `object` omitting the properties the callback returns truey + * for. The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|...string|string[]} [callback] The properties to omit or the + * function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object without the omitted properties. + * @example + * + * _.omit({ 'name': 'fred', 'age': 40 }, 'age'); + * // => { 'name': 'fred' } + * + * _.omit({ 'name': 'fred', 'age': 40 }, function(value) { + * return typeof value == 'number'; + * }); + * // => { 'name': 'fred' } + */ + function omit(object, callback, thisArg) { + var result = {}; + if (typeof callback != 'function') { + var props = []; + forIn(object, function(value, key) { + props.push(key); + }); + props = baseDifference(props, baseFlatten(arguments, true, false, 1)); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + result[key] = object[key]; + } + } else { + callback = lodash.createCallback(callback, thisArg, 3); + forIn(object, function(value, key, object) { + if (!callback(value, key, object)) { + result[key] = value; + } + }); + } + return result; + } + + /** + * Creates a two dimensional array of an object's key-value pairs, + * i.e. `[[key1, value1], [key2, value2]]`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns new array of key-value pairs. + * @example + * + * _.pairs({ 'barney': 36, 'fred': 40 }); + * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments) + */ + function pairs(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + var key = props[index]; + result[index] = [key, object[key]]; + } + return result; + } + + /** + * Creates a shallow clone of `object` composed of the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If a callback is provided it will be executed for each + * property of `object` picking the properties the callback returns truey + * for. The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|...string|string[]} [callback] The function called per + * iteration or property names to pick, specified as individual property + * names or arrays of property names. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object composed of the picked properties. + * @example + * + * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name'); + * // => { 'name': 'fred' } + * + * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) { + * return key.charAt(0) != '_'; + * }); + * // => { 'name': 'fred' } + */ + function pick(object, callback, thisArg) { + var result = {}; + if (typeof callback != 'function') { + var index = -1, + props = baseFlatten(arguments, true, false, 1), + length = isObject(object) ? props.length : 0; + + while (++index < length) { + var key = props[index]; + if (key in object) { + result[key] = object[key]; + } + } + } else { + callback = lodash.createCallback(callback, thisArg, 3); + forIn(object, function(value, key, object) { + if (callback(value, key, object)) { + result[key] = value; + } + }); + } + return result; + } + + /** + * An alternative to `_.reduce` this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable properties through a callback, with each callback execution + * potentially mutating the `accumulator` object. The callback is bound to + * `thisArg` and invoked with four arguments; (accumulator, value, key, object). + * Callbacks may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { + * num *= num; + * if (num % 2) { + * return result.push(num) < 3; + * } + * }); + * // => [1, 9, 25] + * + * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { + * result[key] = num * 3; + * }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function transform(object, callback, accumulator, thisArg) { + var isArr = isArray(object); + if (accumulator == null) { + if (isArr) { + accumulator = []; + } else { + var ctor = object && object.constructor, + proto = ctor && ctor.prototype; + + accumulator = baseCreate(proto); + } + } + if (callback) { + callback = lodash.createCallback(callback, thisArg, 4); + (isArr ? forEach : forOwn)(object, function(value, index, object) { + return callback(accumulator, value, index, object); + }); + } + return accumulator; + } + + /** + * Creates an array composed of the own enumerable property values of `object`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property values. + * @example + * + * _.values({ 'one': 1, 'two': 2, 'three': 3 }); + * // => [1, 2, 3] (property order is not guaranteed across environments) + */ + function values(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + result[index] = object[props[index]]; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array of elements from the specified indexes, or keys, of the + * `collection`. Indexes may be specified as individual arguments or as arrays + * of indexes. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(number|number[]|string|string[])} [index] The indexes of `collection` + * to retrieve, specified as individual indexes or arrays of indexes. + * @returns {Array} Returns a new array of elements corresponding to the + * provided indexes. + * @example + * + * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); + * // => ['a', 'c', 'e'] + * + * _.at(['fred', 'barney', 'pebbles'], 0, 2); + * // => ['fred', 'pebbles'] + */ + function at(collection) { + var args = arguments, + index = -1, + props = baseFlatten(args, true, false, 1), + length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length, + result = Array(length); + + while(++index < length) { + result[index] = collection[props[index]]; + } + return result; + } + + /** + * Checks if a given value is present in a collection using strict equality + * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the + * offset from the end of the collection. + * + * @static + * @memberOf _ + * @alias include + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {*} target The value to check for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {boolean} Returns `true` if the `target` element is found, else `false`. + * @example + * + * _.contains([1, 2, 3], 1); + * // => true + * + * _.contains([1, 2, 3], 1, 2); + * // => false + * + * _.contains({ 'name': 'fred', 'age': 40 }, 'fred'); + * // => true + * + * _.contains('pebbles', 'eb'); + * // => true + */ + function contains(collection, target, fromIndex) { + var index = -1, + indexOf = getIndexOf(), + length = collection ? collection.length : 0, + result = false; + + fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; + if (isArray(collection)) { + result = indexOf(collection, target, fromIndex) > -1; + } else if (typeof length == 'number') { + result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1; + } else { + forOwn(collection, function(value) { + if (++index >= fromIndex) { + return !(result = value === target); + } + }); + } + return result; + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through the callback. The corresponding value + * of each key is the number of times the key was returned by the callback. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); + }); + + /** + * Checks if the given callback returns truey value for **all** elements of + * a collection. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias all + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if all elements passed the callback check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes']); + * // => false + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.every(characters, 'age'); + * // => true + * + * // using "_.where" callback shorthand + * _.every(characters, { 'age': 36 }); + * // => false + */ + function every(collection, callback, thisArg) { + var result = true; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + if (!(result = !!callback(collection[index], index, collection))) { + break; + } + } + } else { + forOwn(collection, function(value, index, collection) { + return (result = !!callback(value, index, collection)); + }); + } + return result; + } + + /** + * Iterates over elements of a collection, returning an array of all elements + * the callback returns truey for. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias select + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that passed the callback check. + * @example + * + * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [2, 4, 6] + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.filter(characters, 'blocked'); + * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] + * + * // using "_.where" callback shorthand + * _.filter(characters, { 'age': 36 }); + * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] + */ + function filter(collection, callback, thisArg) { + var result = []; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + if (callback(value, index, collection)) { + result.push(value); + } + } + } else { + forOwn(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result.push(value); + } + }); + } + return result; + } + + /** + * Iterates over elements of a collection, returning the first element that + * the callback returns truey for. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias detect, findWhere + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the found element, else `undefined`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true }, + * { 'name': 'pebbles', 'age': 1, 'blocked': false } + * ]; + * + * _.find(characters, function(chr) { + * return chr.age < 40; + * }); + * // => { 'name': 'barney', 'age': 36, 'blocked': false } + * + * // using "_.where" callback shorthand + * _.find(characters, { 'age': 1 }); + * // => { 'name': 'pebbles', 'age': 1, 'blocked': false } + * + * // using "_.pluck" callback shorthand + * _.find(characters, 'blocked'); + * // => { 'name': 'fred', 'age': 40, 'blocked': true } + */ + function find(collection, callback, thisArg) { + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + if (callback(value, index, collection)) { + return value; + } + } + } else { + var result; + forOwn(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result = value; + return false; + } + }); + return result; + } + } + + /** + * This method is like `_.find` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the found element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(num) { + * return num % 2 == 1; + * }); + * // => 3 + */ + function findLast(collection, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forEachRight(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result = value; + return false; + } + }); + return result; + } + + /** + * Iterates over elements of a collection, executing the callback for each + * element. The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). Callbacks may exit iteration early by + * explicitly returning `false`. + * + * Note: As with other "Collections" methods, objects with a `length` property + * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` + * may be used for object iteration. + * + * @static + * @memberOf _ + * @alias each + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); + * // => logs each number and returns '1,2,3' + * + * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); + * // => logs each number and returns the object (property order is not guaranteed across environments) + */ + function forEach(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0; + + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + if (typeof length == 'number') { + while (++index < length) { + if (callback(collection[index], index, collection) === false) { + break; + } + } + } else { + forOwn(collection, callback); + } + return collection; + } + + /** + * This method is like `_.forEach` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @alias eachRight + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); + * // => logs each number from right to left and returns '3,2,1' + */ + function forEachRight(collection, callback, thisArg) { + var length = collection ? collection.length : 0; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + if (typeof length == 'number') { + while (length--) { + if (callback(collection[length], length, collection) === false) { + break; + } + } + } else { + var props = keys(collection); + length = props.length; + forOwn(collection, function(value, key, collection) { + key = props ? props[--length] : --length; + return callback(collection[key], key, collection); + }); + } + return collection; + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of a collection through the callback. The corresponding value + * of each key is an array of the elements responsible for generating the key. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false` + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * // using "_.pluck" callback shorthand + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of the collection through the given callback. The corresponding + * value of each key is the last element responsible for generating the key. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var keys = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.indexBy(keys, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + */ + var indexBy = createAggregator(function(result, value, key) { + result[key] = value; + }); + + /** + * Invokes the method named by `methodName` on each element in the `collection` + * returning an array of the results of each invoked method. Additional arguments + * will be provided to each invoked method. If `methodName` is a function it + * will be invoked for, and `this` bound to, each element in the `collection`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|string} methodName The name of the method to invoke or + * the function invoked per iteration. + * @param {...*} [arg] Arguments to invoke the method with. + * @returns {Array} Returns a new array of the results of each invoked method. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + function invoke(collection, methodName) { + var args = slice(arguments, 2), + index = -1, + isFunc = typeof methodName == 'function', + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + forEach(collection, function(value) { + result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); + }); + return result; + } + + /** + * Creates an array of values by running each element in the collection + * through the callback. The callback is bound to `thisArg` and invoked with + * three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias collect + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of the results of each `callback` execution. + * @example + * + * _.map([1, 2, 3], function(num) { return num * 3; }); + * // => [3, 6, 9] + * + * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); + * // => [3, 6, 9] (property order is not guaranteed across environments) + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.map(characters, 'name'); + * // => ['barney', 'fred'] + */ + function map(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + if (typeof length == 'number') { + var result = Array(length); + while (++index < length) { + result[index] = callback(collection[index], index, collection); + } + } else { + result = []; + forOwn(collection, function(value, key, collection) { + result[++index] = callback(value, key, collection); + }); + } + return result; + } + + /** + * Retrieves the maximum value of a collection. If the collection is empty or + * falsey `-Infinity` is returned. If a callback is provided it will be executed + * for each value in the collection to generate the criterion by which the value + * is ranked. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.max(characters, function(chr) { return chr.age; }); + * // => { 'name': 'fred', 'age': 40 }; + * + * // using "_.pluck" callback shorthand + * _.max(characters, 'age'); + * // => { 'name': 'fred', 'age': 40 }; + */ + function max(collection, callback, thisArg) { + var computed = -Infinity, + result = computed; + + // allows working with functions like `_.map` without using + // their `index` argument as a callback + if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { + callback = null; + } + if (callback == null && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (value > result) { + result = value; + } + } + } else { + callback = (callback == null && isString(collection)) + ? charAtCallback + : lodash.createCallback(callback, thisArg, 3); + + forEach(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current > computed) { + computed = current; + result = value; + } + }); + } + return result; + } + + /** + * Retrieves the minimum value of a collection. If the collection is empty or + * falsey `Infinity` is returned. If a callback is provided it will be executed + * for each value in the collection to generate the criterion by which the value + * is ranked. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.min(characters, function(chr) { return chr.age; }); + * // => { 'name': 'barney', 'age': 36 }; + * + * // using "_.pluck" callback shorthand + * _.min(characters, 'age'); + * // => { 'name': 'barney', 'age': 36 }; + */ + function min(collection, callback, thisArg) { + var computed = Infinity, + result = computed; + + // allows working with functions like `_.map` without using + // their `index` argument as a callback + if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { + callback = null; + } + if (callback == null && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (value < result) { + result = value; + } + } + } else { + callback = (callback == null && isString(collection)) + ? charAtCallback + : lodash.createCallback(callback, thisArg, 3); + + forEach(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current < computed) { + computed = current; + result = value; + } + }); + } + return result; + } + + /** + * Retrieves the value of a specified property from all elements in the collection. + * + * @static + * @memberOf _ + * @type Function + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {string} property The name of the property to pluck. + * @returns {Array} Returns a new array of property values. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.pluck(characters, 'name'); + * // => ['barney', 'fred'] + */ + var pluck = map; + + /** + * Reduces a collection to a value which is the accumulated result of running + * each element in the collection through the callback, where each successive + * callback execution consumes the return value of the previous execution. If + * `accumulator` is not provided the first element of the collection will be + * used as the initial `accumulator` value. The callback is bound to `thisArg` + * and invoked with four arguments; (accumulator, value, index|key, collection). + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] Initial value of the accumulator. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var sum = _.reduce([1, 2, 3], function(sum, num) { + * return sum + num; + * }); + * // => 6 + * + * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { + * result[key] = num * 3; + * return result; + * }, {}); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function reduce(collection, callback, accumulator, thisArg) { + if (!collection) return accumulator; + var noaccum = arguments.length < 3; + callback = lodash.createCallback(callback, thisArg, 4); + + var index = -1, + length = collection.length; + + if (typeof length == 'number') { + if (noaccum) { + accumulator = collection[++index]; + } + while (++index < length) { + accumulator = callback(accumulator, collection[index], index, collection); + } + } else { + forOwn(collection, function(value, index, collection) { + accumulator = noaccum + ? (noaccum = false, value) + : callback(accumulator, value, index, collection) + }); + } + return accumulator; + } + + /** + * This method is like `_.reduce` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] Initial value of the accumulator. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var list = [[0, 1], [2, 3], [4, 5]]; + * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, callback, accumulator, thisArg) { + var noaccum = arguments.length < 3; + callback = lodash.createCallback(callback, thisArg, 4); + forEachRight(collection, function(value, index, collection) { + accumulator = noaccum + ? (noaccum = false, value) + : callback(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The opposite of `_.filter` this method returns the elements of a + * collection that the callback does **not** return truey for. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that failed the callback check. + * @example + * + * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [1, 3, 5] + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.reject(characters, 'blocked'); + * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] + * + * // using "_.where" callback shorthand + * _.reject(characters, { 'age': 36 }); + * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] + */ + function reject(collection, callback, thisArg) { + callback = lodash.createCallback(callback, thisArg, 3); + return filter(collection, function(value, index, collection) { + return !callback(value, index, collection); + }); + } + + /** + * Retrieves a random element or `n` random elements from a collection. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to sample. + * @param {number} [n] The number of elements to sample. + * @param- {Object} [guard] Allows working with functions like `_.map` + * without using their `index` arguments as `n`. + * @returns {Array} Returns the random sample(s) of `collection`. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + * + * _.sample([1, 2, 3, 4], 2); + * // => [3, 1] + */ + function sample(collection, n, guard) { + if (collection && typeof collection.length != 'number') { + collection = values(collection); + } + if (n == null || guard) { + return collection ? collection[baseRandom(0, collection.length - 1)] : undefined; + } + var result = shuffle(collection); + result.length = nativeMin(nativeMax(0, n), result.length); + return result; + } + + /** + * Creates an array of shuffled values, using a version of the Fisher-Yates + * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to shuffle. + * @returns {Array} Returns a new shuffled collection. + * @example + * + * _.shuffle([1, 2, 3, 4, 5, 6]); + * // => [4, 1, 6, 3, 5, 2] + */ + function shuffle(collection) { + var index = -1, + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + forEach(collection, function(value) { + var rand = baseRandom(0, ++index); + result[index] = result[rand]; + result[rand] = value; + }); + return result; + } + + /** + * Gets the size of the `collection` by returning `collection.length` for arrays + * and array-like objects or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns `collection.length` or number of own enumerable properties. + * @example + * + * _.size([1, 2]); + * // => 2 + * + * _.size({ 'one': 1, 'two': 2, 'three': 3 }); + * // => 3 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + var length = collection ? collection.length : 0; + return typeof length == 'number' ? length : keys(collection).length; + } + + /** + * Checks if the callback returns a truey value for **any** element of a + * collection. The function returns as soon as it finds a passing value and + * does not iterate over the entire collection. The callback is bound to + * `thisArg` and invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias any + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if any element passed the callback check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.some(characters, 'blocked'); + * // => true + * + * // using "_.where" callback shorthand + * _.some(characters, { 'age': 1 }); + * // => false + */ + function some(collection, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + if ((result = callback(collection[index], index, collection))) { + break; + } + } + } else { + forOwn(collection, function(value, index, collection) { + return !(result = callback(value, index, collection)); + }); + } + return !!result; + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through the callback. This method + * performs a stable sort, that is, it will preserve the original sort order + * of equal elements. The callback is bound to `thisArg` and invoked with + * three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an array of property names is provided for `callback` the collection + * will be sorted by each property value. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of sorted elements. + * @example + * + * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); + * // => [3, 1, 2] + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 }, + * { 'name': 'barney', 'age': 26 }, + * { 'name': 'fred', 'age': 30 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.map(_.sortBy(characters, 'age'), _.values); + * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] + * + * // sorting by multiple properties + * _.map(_.sortBy(characters, ['name', 'age']), _.values); + * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] + */ + function sortBy(collection, callback, thisArg) { + var index = -1, + isArr = isArray(callback), + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + if (!isArr) { + callback = lodash.createCallback(callback, thisArg, 3); + } + forEach(collection, function(value, key, collection) { + var object = result[++index] = getObject(); + if (isArr) { + object.criteria = map(callback, function(key) { return value[key]; }); + } else { + (object.criteria = getArray())[0] = callback(value, key, collection); + } + object.index = index; + object.value = value; + }); + + length = result.length; + result.sort(compareAscending); + while (length--) { + var object = result[length]; + result[length] = object.value; + if (!isArr) { + releaseArray(object.criteria); + } + releaseObject(object); + } + return result; + } + + /** + * Converts the `collection` to an array. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to convert. + * @returns {Array} Returns the new converted array. + * @example + * + * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); + * // => [2, 3, 4] + */ + function toArray(collection) { + if (collection && typeof collection.length == 'number') { + return slice(collection); + } + return values(collection); + } + + /** + * Performs a deep comparison of each element in a `collection` to the given + * `properties` object, returning an array of all elements that have equivalent + * property values. + * + * @static + * @memberOf _ + * @type Function + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Object} props The object of property values to filter by. + * @returns {Array} Returns a new array of elements that have the given properties. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }, + * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } + * ]; + * + * _.where(characters, { 'age': 36 }); + * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }] + * + * _.where(characters, { 'pets': ['dino'] }); + * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }] + */ + var where = filter; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are all falsey. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to compact. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result.push(value); + } + } + return result; + } + + /** + * Creates an array excluding all values of the provided arrays using strict + * equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to process. + * @param {...Array} [values] The arrays of values to exclude. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); + * // => [1, 3, 4] + */ + function difference(array) { + return baseDifference(array, baseFlatten(arguments, true, true, 1)); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element that passes the callback check, instead of the element itself. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true }, + * { 'name': 'pebbles', 'age': 1, 'blocked': false } + * ]; + * + * _.findIndex(characters, function(chr) { + * return chr.age < 20; + * }); + * // => 2 + * + * // using "_.where" callback shorthand + * _.findIndex(characters, { 'age': 36 }); + * // => 0 + * + * // using "_.pluck" callback shorthand + * _.findIndex(characters, 'blocked'); + * // => 1 + */ + function findIndex(array, callback, thisArg) { + var index = -1, + length = array ? array.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length) { + if (callback(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of a `collection` from right to left. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': true }, + * { 'name': 'fred', 'age': 40, 'blocked': false }, + * { 'name': 'pebbles', 'age': 1, 'blocked': true } + * ]; + * + * _.findLastIndex(characters, function(chr) { + * return chr.age > 30; + * }); + * // => 1 + * + * // using "_.where" callback shorthand + * _.findLastIndex(characters, { 'age': 36 }); + * // => 0 + * + * // using "_.pluck" callback shorthand + * _.findLastIndex(characters, 'blocked'); + * // => 2 + */ + function findLastIndex(array, callback, thisArg) { + var length = array ? array.length : 0; + callback = lodash.createCallback(callback, thisArg, 3); + while (length--) { + if (callback(array[length], length, array)) { + return length; + } + } + return -1; + } + + /** + * Gets the first element or first `n` elements of an array. If a callback + * is provided elements at the beginning of the array are returned as long + * as the callback returns truey. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias head, take + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback] The function called + * per element or the number of elements to return. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the first element(s) of `array`. + * @example + * + * _.first([1, 2, 3]); + * // => 1 + * + * _.first([1, 2, 3], 2); + * // => [1, 2] + * + * _.first([1, 2, 3], function(num) { + * return num < 3; + * }); + * // => [1, 2] + * + * var characters = [ + * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.first(characters, 'blocked'); + * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }] + * + * // using "_.where" callback shorthand + * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name'); + * // => ['barney', 'fred'] + */ + function first(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = -1; + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length && callback(array[index], index, array)) { + n++; + } + } else { + n = callback; + if (n == null || thisArg) { + return array ? array[0] : undefined; + } + } + return slice(array, 0, nativeMin(nativeMax(0, n), length)); + } + + /** + * Flattens a nested array (the nesting can be to any depth). If `isShallow` + * is truey, the array will only be flattened a single level. If a callback + * is provided each element of the array is passed through the callback before + * flattening. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to flatten. + * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new flattened array. + * @example + * + * _.flatten([1, [2], [3, [[4]]]]); + * // => [1, 2, 3, 4]; + * + * _.flatten([1, [2], [3, [[4]]]], true); + * // => [1, 2, 3, [[4]]]; + * + * var characters = [ + * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] }, + * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } + * ]; + * + * // using "_.pluck" callback shorthand + * _.flatten(characters, 'pets'); + * // => ['hoppy', 'baby puss', 'dino'] + */ + function flatten(array, isShallow, callback, thisArg) { + // juggle arguments + if (typeof isShallow != 'boolean' && isShallow != null) { + thisArg = callback; + callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow; + isShallow = false; + } + if (callback != null) { + array = map(array, callback, thisArg); + } + return baseFlatten(array, isShallow); + } + + /** + * Gets the index at which the first occurrence of `value` is found using + * strict equality for comparisons, i.e. `===`. If the array is already sorted + * providing `true` for `fromIndex` will run a faster binary search. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=0] The index to search from or `true` + * to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value or `-1`. + * @example + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2); + * // => 1 + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 4 + * + * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); + * // => 2 + */ + function indexOf(array, value, fromIndex) { + if (typeof fromIndex == 'number') { + var length = array ? array.length : 0; + fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); + } else if (fromIndex) { + var index = sortedIndex(array, value); + return array[index] === value ? index : -1; + } + return baseIndexOf(array, value, fromIndex); + } + + /** + * Gets all but the last element or last `n` elements of an array. If a + * callback is provided elements at the end of the array are excluded from + * the result as long as the callback returns truey. The callback is bound + * to `thisArg` and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback=1] The function called + * per element or the number of elements to exclude. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + * + * _.initial([1, 2, 3], 2); + * // => [1] + * + * _.initial([1, 2, 3], function(num) { + * return num > 1; + * }); + * // => [1] + * + * var characters = [ + * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.initial(characters, 'blocked'); + * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }] + * + * // using "_.where" callback shorthand + * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name'); + * // => ['barney', 'fred'] + */ + function initial(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = length; + callback = lodash.createCallback(callback, thisArg, 3); + while (index-- && callback(array[index], index, array)) { + n++; + } + } else { + n = (callback == null || thisArg) ? 1 : callback || n; + } + return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); + } + + /** + * Creates an array of unique values present in all provided arrays using + * strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of shared values. + * @example + * + * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]); + * // => [1, 2] + */ + function intersection() { + var args = [], + argsIndex = -1, + argsLength = arguments.length, + caches = getArray(), + indexOf = getIndexOf(), + trustIndexOf = indexOf === baseIndexOf, + seen = getArray(); + + while (++argsIndex < argsLength) { + var value = arguments[argsIndex]; + if (isArray(value) || isArguments(value)) { + args.push(value); + caches.push(trustIndexOf && value.length >= largeArraySize && + createCache(argsIndex ? args[argsIndex] : seen)); + } + } + var array = args[0], + index = -1, + length = array ? array.length : 0, + result = []; + + outer: + while (++index < length) { + var cache = caches[0]; + value = array[index]; + + if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) { + argsIndex = argsLength; + (cache || seen).push(value); + while (--argsIndex) { + cache = caches[argsIndex]; + if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { + continue outer; + } + } + result.push(value); + } + } + while (argsLength--) { + cache = caches[argsLength]; + if (cache) { + releaseObject(cache); + } + } + releaseArray(caches); + releaseArray(seen); + return result; + } + + /** + * Gets the last element or last `n` elements of an array. If a callback is + * provided elements at the end of the array are returned as long as the + * callback returns truey. The callback is bound to `thisArg` and invoked + * with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback] The function called + * per element or the number of elements to return. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the last element(s) of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + * + * _.last([1, 2, 3], 2); + * // => [2, 3] + * + * _.last([1, 2, 3], function(num) { + * return num > 1; + * }); + * // => [2, 3] + * + * var characters = [ + * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.pluck(_.last(characters, 'blocked'), 'name'); + * // => ['fred', 'pebbles'] + * + * // using "_.where" callback shorthand + * _.last(characters, { 'employer': 'na' }); + * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] + */ + function last(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = length; + callback = lodash.createCallback(callback, thisArg, 3); + while (index-- && callback(array[index], index, array)) { + n++; + } + } else { + n = callback; + if (n == null || thisArg) { + return array ? array[length - 1] : undefined; + } + } + return slice(array, nativeMax(0, length - n)); + } + + /** + * Gets the index at which the last occurrence of `value` is found using strict + * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used + * as the offset from the end of the collection. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value or `-1`. + * @example + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); + * // => 4 + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var index = array ? array.length : 0; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Removes all provided values from the given array using strict equality for + * comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to modify. + * @param {...*} [value] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * _.pull(array, 2, 3); + * console.log(array); + * // => [1, 1] + */ + function pull(array) { + var args = arguments, + argsIndex = 0, + argsLength = args.length, + length = array ? array.length : 0; + + while (++argsIndex < argsLength) { + var index = -1, + value = args[argsIndex]; + while (++index < length) { + if (array[index] === value) { + splice.call(array, index--, 1); + length--; + } + } + } + return array; + } + + /** + * Creates an array of numbers (positive and/or negative) progressing from + * `start` up to but not including `end`. If `start` is less than `stop` a + * zero-length range is created unless a negative `step` is specified. + * + * @static + * @memberOf _ + * @category Arrays + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @param {number} [step=1] The value to increment or decrement by. + * @returns {Array} Returns a new range array. + * @example + * + * _.range(4); + * // => [0, 1, 2, 3] + * + * _.range(1, 5); + * // => [1, 2, 3, 4] + * + * _.range(0, 20, 5); + * // => [0, 5, 10, 15] + * + * _.range(0, -4, -1); + * // => [0, -1, -2, -3] + * + * _.range(1, 4, 0); + * // => [1, 1, 1] + * + * _.range(0); + * // => [] + */ + function range(start, end, step) { + start = +start || 0; + step = typeof step == 'number' ? step : (+step || 1); + + if (end == null) { + end = start; + start = 0; + } + // use `Array(length)` so engines like Chakra and V8 avoid slower modes + // http://youtu.be/XAqIpGU8ZZk#t=17m25s + var index = -1, + length = nativeMax(0, ceil((end - start) / (step || 1))), + result = Array(length); + + while (++index < length) { + result[index] = start; + start += step; + } + return result; + } + + /** + * Removes all elements from an array that the callback returns truey for + * and returns an array of removed elements. The callback is bound to `thisArg` + * and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to modify. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4, 5, 6]; + * var evens = _.remove(array, function(num) { return num % 2 == 0; }); + * + * console.log(array); + * // => [1, 3, 5] + * + * console.log(evens); + * // => [2, 4, 6] + */ + function remove(array, callback, thisArg) { + var index = -1, + length = array ? array.length : 0, + result = []; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length) { + var value = array[index]; + if (callback(value, index, array)) { + result.push(value); + splice.call(array, index--, 1); + length--; + } + } + return result; + } + + /** + * The opposite of `_.initial` this method gets all but the first element or + * first `n` elements of an array. If a callback function is provided elements + * at the beginning of the array are excluded from the result as long as the + * callback returns truey. The callback is bound to `thisArg` and invoked + * with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias drop, tail + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback=1] The function called + * per element or the number of elements to exclude. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a slice of `array`. + * @example + * + * _.rest([1, 2, 3]); + * // => [2, 3] + * + * _.rest([1, 2, 3], 2); + * // => [3] + * + * _.rest([1, 2, 3], function(num) { + * return num < 3; + * }); + * // => [3] + * + * var characters = [ + * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.pluck(_.rest(characters, 'blocked'), 'name'); + * // => ['fred', 'pebbles'] + * + * // using "_.where" callback shorthand + * _.rest(characters, { 'employer': 'slate' }); + * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] + */ + function rest(array, callback, thisArg) { + if (typeof callback != 'number' && callback != null) { + var n = 0, + index = -1, + length = array ? array.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length && callback(array[index], index, array)) { + n++; + } + } else { + n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); + } + return slice(array, n); + } + + /** + * Uses a binary search to determine the smallest index at which a value + * should be inserted into a given sorted array in order to maintain the sort + * order of the array. If a callback is provided it will be executed for + * `value` and each element of `array` to compute their sort ranking. The + * callback is bound to `thisArg` and invoked with one argument; (value). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([20, 30, 50], 40); + * // => 2 + * + * // using "_.pluck" callback shorthand + * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 2 + * + * var dict = { + * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } + * }; + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return dict.wordToNumber[word]; + * }); + * // => 2 + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return this.wordToNumber[word]; + * }, dict); + * // => 2 + */ + function sortedIndex(array, value, callback, thisArg) { + var low = 0, + high = array ? array.length : low; + + // explicitly reference `identity` for better inlining in Firefox + callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; + value = callback(value); + + while (low < high) { + var mid = (low + high) >>> 1; + (callback(array[mid]) < value) + ? low = mid + 1 + : high = mid; + } + return low; + } + + /** + * Creates an array of unique values, in order, of the provided arrays using + * strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of combined values. + * @example + * + * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]); + * // => [1, 2, 3, 5, 4] + */ + function union() { + return baseUniq(baseFlatten(arguments, true, true)); + } + + /** + * Creates a duplicate-value-free version of an array using strict equality + * for comparisons, i.e. `===`. If the array is sorted, providing + * `true` for `isSorted` will use a faster algorithm. If a callback is provided + * each element of `array` is passed through the callback before uniqueness + * is computed. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias unique + * @category Arrays + * @param {Array} array The array to process. + * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a duplicate-value-free array. + * @example + * + * _.uniq([1, 2, 1, 3, 1]); + * // => [1, 2, 3] + * + * _.uniq([1, 1, 2, 2, 3], true); + * // => [1, 2, 3] + * + * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); + * // => ['A', 'b', 'C'] + * + * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); + * // => [1, 2.5, 3] + * + * // using "_.pluck" callback shorthand + * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniq(array, isSorted, callback, thisArg) { + // juggle arguments + if (typeof isSorted != 'boolean' && isSorted != null) { + thisArg = callback; + callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted; + isSorted = false; + } + if (callback != null) { + callback = lodash.createCallback(callback, thisArg, 3); + } + return baseUniq(array, isSorted, callback); + } + + /** + * Creates an array excluding all provided values using strict equality for + * comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to filter. + * @param {...*} [value] The values to exclude. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); + * // => [2, 3, 4] + */ + function without(array) { + return baseDifference(array, slice(arguments, 1)); + } + + /** + * Creates an array that is the symmetric difference of the provided arrays. + * See http://en.wikipedia.org/wiki/Symmetric_difference. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of values. + * @example + * + * _.xor([1, 2, 3], [5, 2, 1, 4]); + * // => [3, 5, 4] + * + * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); + * // => [1, 4, 5] + */ + function xor() { + var index = -1, + length = arguments.length; + + while (++index < length) { + var array = arguments[index]; + if (isArray(array) || isArguments(array)) { + var result = result + ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result))) + : array; + } + } + return result || []; + } + + /** + * Creates an array of grouped elements, the first of which contains the first + * elements of the given arrays, the second of which contains the second + * elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @alias unzip + * @category Arrays + * @param {...Array} [array] Arrays to process. + * @returns {Array} Returns a new array of grouped elements. + * @example + * + * _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + */ + function zip() { + var array = arguments.length > 1 ? arguments : arguments[0], + index = -1, + length = array ? max(pluck(array, 'length')) : 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = pluck(array, index); + } + return result; + } + + /** + * Creates an object composed from arrays of `keys` and `values`. Provide + * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]` + * or two arrays, one of `keys` and one of corresponding `values`. + * + * @static + * @memberOf _ + * @alias object + * @category Arrays + * @param {Array} keys The array of keys. + * @param {Array} [values=[]] The array of values. + * @returns {Object} Returns an object composed of the given keys and + * corresponding values. + * @example + * + * _.zipObject(['fred', 'barney'], [30, 40]); + * // => { 'fred': 30, 'barney': 40 } + */ + function zipObject(keys, values) { + var index = -1, + length = keys ? keys.length : 0, + result = {}; + + if (!values && length && !isArray(keys[0])) { + values = []; + } + while (++index < length) { + var key = keys[index]; + if (values) { + result[key] = values[index]; + } else if (key) { + result[key[0]] = key[1]; + } + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function that executes `func`, with the `this` binding and + * arguments of the created function, only after being called `n` times. + * + * @static + * @memberOf _ + * @category Functions + * @param {number} n The number of times the function must be called before + * `func` is executed. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('Done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => logs 'Done saving!', after all saves have completed + */ + function after(n, func) { + if (!isFunction(func)) { + throw new TypeError; + } + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that, when called, invokes `func` with the `this` + * binding of `thisArg` and prepends any additional `bind` arguments to those + * provided to the bound function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to bind. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var func = function(greeting) { + * return greeting + ' ' + this.name; + * }; + * + * func = _.bind(func, { 'name': 'fred' }, 'hi'); + * func(); + * // => 'hi fred' + */ + function bind(func, thisArg) { + return arguments.length > 2 + ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) + : createWrapper(func, 1, null, null, thisArg); + } + + /** + * Binds methods of an object to the object itself, overwriting the existing + * method. Method names may be specified as individual arguments or as arrays + * of method names. If no method names are provided all the function properties + * of `object` will be bound. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...string} [methodName] The object method names to + * bind, specified as individual method names or arrays of method names. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'onClick': function() { console.log('clicked ' + this.label); } + * }; + * + * _.bindAll(view); + * jQuery('#docs').on('click', view.onClick); + * // => logs 'clicked docs', when the button is clicked + */ + function bindAll(object) { + var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), + index = -1, + length = funcs.length; + + while (++index < length) { + var key = funcs[index]; + object[key] = createWrapper(object[key], 1, null, null, object); + } + return object; + } + + /** + * Creates a function that, when called, invokes the method at `object[key]` + * and prepends any additional `bindKey` arguments to those provided to the bound + * function. This method differs from `_.bind` by allowing bound functions to + * reference methods that will be redefined or don't yet exist. + * See http://michaux.ca/articles/lazy-function-definition-pattern. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object the method belongs to. + * @param {string} key The key of the method. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'name': 'fred', + * 'greet': function(greeting) { + * return greeting + ' ' + this.name; + * } + * }; + * + * var func = _.bindKey(object, 'greet', 'hi'); + * func(); + * // => 'hi fred' + * + * object.greet = function(greeting) { + * return greeting + 'ya ' + this.name + '!'; + * }; + * + * func(); + * // => 'hiya fred!' + */ + function bindKey(object, key) { + return arguments.length > 2 + ? createWrapper(key, 19, slice(arguments, 2), null, object) + : createWrapper(key, 3, null, null, object); + } + + /** + * Creates a function that is the composition of the provided functions, + * where each function consumes the return value of the function that follows. + * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. + * Each function is executed with the `this` binding of the composed function. + * + * @static + * @memberOf _ + * @category Functions + * @param {...Function} [func] Functions to compose. + * @returns {Function} Returns the new composed function. + * @example + * + * var realNameMap = { + * 'pebbles': 'penelope' + * }; + * + * var format = function(name) { + * name = realNameMap[name.toLowerCase()] || name; + * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); + * }; + * + * var greet = function(formatted) { + * return 'Hiya ' + formatted + '!'; + * }; + * + * var welcome = _.compose(greet, format); + * welcome('pebbles'); + * // => 'Hiya Penelope!' + */ + function compose() { + var funcs = arguments, + length = funcs.length; + + while (length--) { + if (!isFunction(funcs[length])) { + throw new TypeError; + } + } + return function() { + var args = arguments, + length = funcs.length; + + while (length--) { + args = [funcs[length].apply(this, args)]; + } + return args[0]; + }; + } + + /** + * Creates a function which accepts one or more arguments of `func` that when + * invoked either executes `func` returning its result, if all `func` arguments + * have been provided, or returns a function that accepts one or more of the + * remaining `func` arguments, and so on. The arity of `func` can be specified + * if `func.length` is not sufficient. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @returns {Function} Returns the new curried function. + * @example + * + * var curried = _.curry(function(a, b, c) { + * console.log(a + b + c); + * }); + * + * curried(1)(2)(3); + * // => 6 + * + * curried(1, 2)(3); + * // => 6 + * + * curried(1, 2, 3); + * // => 6 + */ + function curry(func, arity) { + arity = typeof arity == 'number' ? arity : (+arity || func.length); + return createWrapper(func, 4, null, null, null, arity); + } + + /** + * Creates a function that will delay the execution of `func` until after + * `wait` milliseconds have elapsed since the last time it was invoked. + * Provide an options object to indicate that `func` should be invoked on + * the leading and/or trailing edge of the `wait` timeout. Subsequent calls + * to the debounced function will return the result of the last `func` call. + * + * Note: If `leading` and `trailing` options are `true` `func` will be called + * on the trailing edge of the timeout only if the the debounced function is + * invoked more than once during the `wait` timeout. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to debounce. + * @param {number} wait The number of milliseconds to delay. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout. + * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called. + * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // avoid costly calculations while the window size is in flux + * var lazyLayout = _.debounce(calculateLayout, 150); + * jQuery(window).on('resize', lazyLayout); + * + * // execute `sendMail` when the click event is fired, debouncing subsequent calls + * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * }); + * + * // ensure `batchLog` is executed once after 1 second of debounced calls + * var source = new EventSource('/stream'); + * source.addEventListener('message', _.debounce(batchLog, 250, { + * 'maxWait': 1000 + * }, false); + */ + function debounce(func, wait, options) { + var args, + maxTimeoutId, + result, + stamp, + thisArg, + timeoutId, + trailingCall, + lastCalled = 0, + maxWait = false, + trailing = true; + + if (!isFunction(func)) { + throw new TypeError; + } + wait = nativeMax(0, wait) || 0; + if (options === true) { + var leading = true; + trailing = false; + } else if (isObject(options)) { + leading = options.leading; + maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); + trailing = 'trailing' in options ? options.trailing : trailing; + } + var delayed = function() { + var remaining = wait - (now() - stamp); + if (remaining <= 0) { + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + var isCalled = trailingCall; + maxTimeoutId = timeoutId = trailingCall = undefined; + if (isCalled) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + } else { + timeoutId = setTimeout(delayed, remaining); + } + }; + + var maxDelayed = function() { + if (timeoutId) { + clearTimeout(timeoutId); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + if (trailing || (maxWait !== wait)) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + }; + + return function() { + args = arguments; + stamp = now(); + thisArg = this; + trailingCall = trailing && (timeoutId || !leading); + + if (maxWait === false) { + var leadingCall = leading && !timeoutId; + } else { + if (!maxTimeoutId && !leading) { + lastCalled = stamp; + } + var remaining = maxWait - (stamp - lastCalled), + isCalled = remaining <= 0; + + if (isCalled) { + if (maxTimeoutId) { + maxTimeoutId = clearTimeout(maxTimeoutId); + } + lastCalled = stamp; + result = func.apply(thisArg, args); + } + else if (!maxTimeoutId) { + maxTimeoutId = setTimeout(maxDelayed, remaining); + } + } + if (isCalled && timeoutId) { + timeoutId = clearTimeout(timeoutId); + } + else if (!timeoutId && wait !== maxWait) { + timeoutId = setTimeout(delayed, wait); + } + if (leadingCall) { + isCalled = true; + result = func.apply(thisArg, args); + } + if (isCalled && !timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + return result; + }; + } + + /** + * Defers executing the `func` function until the current call stack has cleared. + * Additional arguments will be provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to defer. + * @param {...*} [arg] Arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { console.log(text); }, 'deferred'); + * // logs 'deferred' after one or more milliseconds + */ + function defer(func) { + if (!isFunction(func)) { + throw new TypeError; + } + var args = slice(arguments, 1); + return setTimeout(function() { func.apply(undefined, args); }, 1); + } + + /** + * Executes the `func` function after `wait` milliseconds. Additional arguments + * will be provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay execution. + * @param {...*} [arg] Arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { console.log(text); }, 1000, 'later'); + * // => logs 'later' after one second + */ + function delay(func, wait) { + if (!isFunction(func)) { + throw new TypeError; + } + var args = slice(arguments, 2); + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided it will be used to determine the cache key for storing the result + * based on the arguments provided to the memoized function. By default, the + * first argument provided to the memoized function is used as the cache key. + * The `func` is executed with the `this` binding of the memoized function. + * The result cache is exposed as the `cache` property on the memoized function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] A function used to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var fibonacci = _.memoize(function(n) { + * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); + * }); + * + * fibonacci(9) + * // => 34 + * + * var data = { + * 'fred': { 'name': 'fred', 'age': 40 }, + * 'pebbles': { 'name': 'pebbles', 'age': 1 } + * }; + * + * // modifying the result cache + * var get = _.memoize(function(name) { return data[name]; }, _.identity); + * get('pebbles'); + * // => { 'name': 'pebbles', 'age': 1 } + * + * get.cache.pebbles.name = 'penelope'; + * get('pebbles'); + * // => { 'name': 'penelope', 'age': 1 } + */ + function memoize(func, resolver) { + if (!isFunction(func)) { + throw new TypeError; + } + var memoized = function() { + var cache = memoized.cache, + key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; + + return hasOwnProperty.call(cache, key) + ? cache[key] + : (cache[key] = func.apply(this, arguments)); + } + memoized.cache = {}; + return memoized; + } + + /** + * Creates a function that is restricted to execute `func` once. Repeat calls to + * the function will return the value of the first call. The `func` is executed + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // `initialize` executes `createApplication` once + */ + function once(func) { + var ran, + result; + + if (!isFunction(func)) { + throw new TypeError; + } + return function() { + if (ran) { + return result; + } + ran = true; + result = func.apply(this, arguments); + + // clear the `func` variable so the function may be garbage collected + func = null; + return result; + }; + } + + /** + * Creates a function that, when called, invokes `func` with any additional + * `partial` arguments prepended to those provided to the new function. This + * method is similar to `_.bind` except it does **not** alter the `this` binding. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { return greeting + ' ' + name; }; + * var hi = _.partial(greet, 'hi'); + * hi('fred'); + * // => 'hi fred' + */ + function partial(func) { + return createWrapper(func, 16, slice(arguments, 1)); + } + + /** + * This method is like `_.partial` except that `partial` arguments are + * appended to those provided to the new function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var defaultsDeep = _.partialRight(_.merge, _.defaults); + * + * var options = { + * 'variable': 'data', + * 'imports': { 'jq': $ } + * }; + * + * defaultsDeep(options, _.templateSettings); + * + * options.variable + * // => 'data' + * + * options.imports + * // => { '_': _, 'jq': $ } + */ + function partialRight(func) { + return createWrapper(func, 32, null, slice(arguments, 1)); + } + + /** + * Creates a function that, when executed, will only call the `func` function + * at most once per every `wait` milliseconds. Provide an options object to + * indicate that `func` should be invoked on the leading and/or trailing edge + * of the `wait` timeout. Subsequent calls to the throttled function will + * return the result of the last `func` call. + * + * Note: If `leading` and `trailing` options are `true` `func` will be called + * on the trailing edge of the timeout only if the the throttled function is + * invoked more than once during the `wait` timeout. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to throttle. + * @param {number} wait The number of milliseconds to throttle executions to. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // avoid excessively updating the position while scrolling + * var throttled = _.throttle(updatePosition, 100); + * jQuery(window).on('scroll', throttled); + * + * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes + * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { + * 'trailing': false + * })); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (!isFunction(func)) { + throw new TypeError; + } + if (options === false) { + leading = false; + } else if (isObject(options)) { + leading = 'leading' in options ? options.leading : leading; + trailing = 'trailing' in options ? options.trailing : trailing; + } + debounceOptions.leading = leading; + debounceOptions.maxWait = wait; + debounceOptions.trailing = trailing; + + return debounce(func, wait, debounceOptions); + } + + /** + * Creates a function that provides `value` to the wrapper function as its + * first argument. Additional arguments provided to the function are appended + * to those provided to the wrapper function. The wrapper is executed with + * the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {*} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('Fred, Wilma, & Pebbles'); + * // => '

Fred, Wilma, & Pebbles

' + */ + function wrap(value, wrapper) { + return createWrapper(wrapper, 16, [value]); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new function. + * @example + * + * var object = { 'name': 'fred' }; + * var getter = _.constant(object); + * getter() === object; + * // => true + */ + function constant(value) { + return function() { + return value; + }; + } + + /** + * Produces a callback bound to an optional `thisArg`. If `func` is a property + * name the created callback will return the property value for a given element. + * If `func` is an object the created callback will return `true` for elements + * that contain the equivalent object properties, otherwise it will return `false`. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} [func=identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of the created callback. + * @param {number} [argCount] The number of arguments the callback accepts. + * @returns {Function} Returns a callback function. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // wrap to create custom callback shorthands + * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { + * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); + * return !match ? func(callback, thisArg) : function(object) { + * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; + * }; + * }); + * + * _.filter(characters, 'age__gt38'); + * // => [{ 'name': 'fred', 'age': 40 }] + */ + function createCallback(func, thisArg, argCount) { + var type = typeof func; + if (func == null || type == 'function') { + return baseCreateCallback(func, thisArg, argCount); + } + // handle "_.pluck" style callback shorthands + if (type != 'object') { + return property(func); + } + var props = keys(func), + key = props[0], + a = func[key]; + + // handle "_.where" style callback shorthands + if (props.length == 1 && a === a && !isObject(a)) { + // fast path the common case of providing an object with a single + // property containing a primitive value + return function(object) { + var b = object[key]; + return a === b && (a !== 0 || (1 / a == 1 / b)); + }; + } + return function(object) { + var length = props.length, + result = false; + + while (length--) { + if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) { + break; + } + } + return result; + }; + } + + /** + * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their + * corresponding HTML entities. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} string The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('Fred, Wilma, & Pebbles'); + * // => 'Fred, Wilma, & Pebbles' + */ + function escape(string) { + return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); + } + + /** + * This method returns the first argument provided to it. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'name': 'fred' }; + * _.identity(object) === object; + * // => true + */ + function identity(value) { + return value; + } + + /** + * Adds function properties of a source object to the destination object. + * If `object` is a function methods will be added to its prototype as well. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Function|Object} [object=lodash] object The destination object. + * @param {Object} source The object of functions to add. + * @param {Object} [options] The options object. + * @param {boolean} [options.chain=true] Specify whether the functions added are chainable. + * @example + * + * function capitalize(string) { + * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); + * } + * + * _.mixin({ 'capitalize': capitalize }); + * _.capitalize('fred'); + * // => 'Fred' + * + * _('fred').capitalize().value(); + * // => 'Fred' + * + * _.mixin({ 'capitalize': capitalize }, { 'chain': false }); + * _('fred').capitalize(); + * // => 'Fred' + */ + function mixin(object, source, options) { + var chain = true, + methodNames = source && functions(source); + + if (!source || (!options && !methodNames.length)) { + if (options == null) { + options = source; + } + ctor = lodashWrapper; + source = object; + object = lodash; + methodNames = functions(source); + } + if (options === false) { + chain = false; + } else if (isObject(options) && 'chain' in options) { + chain = options.chain; + } + var ctor = object, + isFunc = isFunction(ctor); + + forEach(methodNames, function(methodName) { + var func = object[methodName] = source[methodName]; + if (isFunc) { + ctor.prototype[methodName] = function() { + var chainAll = this.__chain__, + value = this.__wrapped__, + args = [value]; + + push.apply(args, arguments); + var result = func.apply(object, args); + if (chain || chainAll) { + if (value === result && isObject(result)) { + return this; + } + result = new ctor(result); + result.__chain__ = chainAll; + } + return result; + }; + } + }); + } + + /** + * Reverts the '_' variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @memberOf _ + * @category Utilities + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + context._ = oldDash; + return this; + } + + /** + * A no-operation function. + * + * @static + * @memberOf _ + * @category Utilities + * @example + * + * var object = { 'name': 'fred' }; + * _.noop(object) === undefined; + * // => true + */ + function noop() { + // no operation performed + } + + /** + * Gets the number of milliseconds that have elapsed since the Unix epoch + * (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @category Utilities + * @example + * + * var stamp = _.now(); + * _.defer(function() { console.log(_.now() - stamp); }); + * // => logs the number of milliseconds it took for the deferred function to be called + */ + var now = isNative(now = Date.now) && now || function() { + return new Date().getTime(); + }; + + /** + * Converts the given value into an integer of the specified radix. + * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the + * `value` is a hexadecimal, in which case a `radix` of `16` is used. + * + * Note: This method avoids differences in native ES3 and ES5 `parseInt` + * implementations. See http://es5.github.io/#E. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} value The value to parse. + * @param {number} [radix] The radix used to interpret the value to parse. + * @returns {number} Returns the new integer value. + * @example + * + * _.parseInt('08'); + * // => 8 + */ + var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) { + // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt` + return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0); + }; + + /** + * Creates a "_.pluck" style function, which returns the `key` value of a + * given object. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} key The name of the property to retrieve. + * @returns {Function} Returns the new function. + * @example + * + * var characters = [ + * { 'name': 'fred', 'age': 40 }, + * { 'name': 'barney', 'age': 36 } + * ]; + * + * var getName = _.property('name'); + * + * _.map(characters, getName); + * // => ['barney', 'fred'] + * + * _.sortBy(characters, getName); + * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] + */ + function property(key) { + return function(object) { + return object[key]; + }; + } + + /** + * Produces a random number between `min` and `max` (inclusive). If only one + * argument is provided a number between `0` and the given number will be + * returned. If `floating` is truey or either `min` or `max` are floats a + * floating-point number will be returned instead of an integer. + * + * @static + * @memberOf _ + * @category Utilities + * @param {number} [min=0] The minimum possible value. + * @param {number} [max=1] The maximum possible value. + * @param {boolean} [floating=false] Specify returning a floating-point number. + * @returns {number} Returns a random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(min, max, floating) { + var noMin = min == null, + noMax = max == null; + + if (floating == null) { + if (typeof min == 'boolean' && noMax) { + floating = min; + min = 1; + } + else if (!noMax && typeof max == 'boolean') { + floating = max; + noMax = true; + } + } + if (noMin && noMax) { + max = 1; + } + min = +min || 0; + if (noMax) { + max = min; + min = 0; + } else { + max = +max || 0; + } + if (floating || min % 1 || max % 1) { + var rand = nativeRandom(); + return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max); + } + return baseRandom(min, max); + } + + /** + * Resolves the value of property `key` on `object`. If `key` is a function + * it will be invoked with the `this` binding of `object` and its result returned, + * else the property value is returned. If `object` is falsey then `undefined` + * is returned. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} object The object to inspect. + * @param {string} key The name of the property to resolve. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { + * 'cheese': 'crumpets', + * 'stuff': function() { + * return 'nonsense'; + * } + * }; + * + * _.result(object, 'cheese'); + * // => 'crumpets' + * + * _.result(object, 'stuff'); + * // => 'nonsense' + */ + function result(object, key) { + if (object) { + var value = object[key]; + return isFunction(value) ? object[key]() : value; + } + } + + /** + * A micro-templating method that handles arbitrary delimiters, preserves + * whitespace, and correctly escapes quotes within interpolated code. + * + * Note: In the development build, `_.template` utilizes sourceURLs for easier + * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl + * + * For more information on precompiling templates see: + * http://lodash.com/custom-builds + * + * For more information on Chrome extension sandboxes see: + * http://developer.chrome.com/stable/extensions/sandboxingEval.html + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} text The template text. + * @param {Object} data The data object used to populate the text. + * @param {Object} [options] The options object. + * @param {RegExp} [options.escape] The "escape" delimiter. + * @param {RegExp} [options.evaluate] The "evaluate" delimiter. + * @param {Object} [options.imports] An object to import into the template as local variables. + * @param {RegExp} [options.interpolate] The "interpolate" delimiter. + * @param {string} [sourceURL] The sourceURL of the template's compiled source. + * @param {string} [variable] The data object variable name. + * @returns {Function|string} Returns a compiled function when no `data` object + * is given, else it returns the interpolated text. + * @example + * + * // using the "interpolate" delimiter to create a compiled template + * var compiled = _.template('hello <%= name %>'); + * compiled({ 'name': 'fred' }); + * // => 'hello fred' + * + * // using the "escape" delimiter to escape HTML in data property values + * _.template('<%- value %>', { 'value': '