diff --git a/docs/assets/main.js b/docs/assets/main.js index 35728810..21a5d74d 100644 --- a/docs/assets/main.js +++ b/docs/assets/main.js @@ -3,7 +3,7 @@ window.translations={"copy":"Copy","copied":"Copied!","normally_hidden":"This me "use strict";(()=>{var Pe=Object.create;var ie=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var Fe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var De=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _e(e))!Me.call(t,i)&&i!==n&&ie(t,i,{get:()=>e[i],enumerable:!(r=Oe(e,i))||r.enumerable});return t};var Ae=(t,e,n)=>(n=t!=null?Pe(Re(t)):{},De(e||!t||!t.__esModule?ie(n,"default",{value:t,enumerable:!0}):n,t));var ue=Fe((ae,le)=>{(function(){var t=function(e){var n=new t.Builder;return n.pipeline.add(t.trimmer,t.stopWordFilter,t.stemmer),n.searchPipeline.add(t.stemmer),e.call(n,n),n.build()};t.version="2.3.9";t.utils={},t.utils.warn=function(e){return function(n){e.console&&console.warn&&console.warn(n)}}(this),t.utils.asString=function(e){return e==null?"":e.toString()},t.utils.clone=function(e){if(e==null)return e;for(var n=Object.create(null),r=Object.keys(e),i=0;i0){var d=t.utils.clone(n)||{};d.position=[a,u],d.index=s.length,s.push(new t.Token(r.slice(a,o),d))}a=o+1}}return s},t.tokenizer.separator=/[\s\-]+/;t.Pipeline=function(){this._stack=[]},t.Pipeline.registeredFunctions=Object.create(null),t.Pipeline.registerFunction=function(e,n){n in this.registeredFunctions&&t.utils.warn("Overwriting existing registered function: "+n),e.label=n,t.Pipeline.registeredFunctions[e.label]=e},t.Pipeline.warnIfFunctionNotRegistered=function(e){var n=e.label&&e.label in this.registeredFunctions;n||t.utils.warn(`Function is not registered with pipeline. This may cause problems when serialising the index. `,e)},t.Pipeline.load=function(e){var n=new t.Pipeline;return e.forEach(function(r){var i=t.Pipeline.registeredFunctions[r];if(i)n.add(i);else throw new Error("Cannot load unregistered function: "+r)}),n},t.Pipeline.prototype.add=function(){var e=Array.prototype.slice.call(arguments);e.forEach(function(n){t.Pipeline.warnIfFunctionNotRegistered(n),this._stack.push(n)},this)},t.Pipeline.prototype.after=function(e,n){t.Pipeline.warnIfFunctionNotRegistered(n);var r=this._stack.indexOf(e);if(r==-1)throw new Error("Cannot find existingFn");r=r+1,this._stack.splice(r,0,n)},t.Pipeline.prototype.before=function(e,n){t.Pipeline.warnIfFunctionNotRegistered(n);var r=this._stack.indexOf(e);if(r==-1)throw new Error("Cannot find existingFn");this._stack.splice(r,0,n)},t.Pipeline.prototype.remove=function(e){var n=this._stack.indexOf(e);n!=-1&&this._stack.splice(n,1)},t.Pipeline.prototype.run=function(e){for(var n=this._stack.length,r=0;r1&&(oe&&(r=s),o!=e);)i=r-n,s=n+Math.floor(i/2),o=this.elements[s*2];if(o==e||o>e)return s*2;if(ol?d+=2:a==l&&(n+=r[u+1]*i[d+1],u+=2,d+=2);return n},t.Vector.prototype.similarity=function(e){return this.dot(e)/this.magnitude()||0},t.Vector.prototype.toArray=function(){for(var e=new Array(this.elements.length/2),n=1,r=0;n0){var o=s.str.charAt(0),a;o in s.node.edges?a=s.node.edges[o]:(a=new t.TokenSet,s.node.edges[o]=a),s.str.length==1&&(a.final=!0),i.push({node:a,editsRemaining:s.editsRemaining,str:s.str.slice(1)})}if(s.editsRemaining!=0){if("*"in s.node.edges)var l=s.node.edges["*"];else{var l=new t.TokenSet;s.node.edges["*"]=l}if(s.str.length==0&&(l.final=!0),i.push({node:l,editsRemaining:s.editsRemaining-1,str:s.str}),s.str.length>1&&i.push({node:s.node,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)}),s.str.length==1&&(s.node.final=!0),s.str.length>=1){if("*"in s.node.edges)var u=s.node.edges["*"];else{var u=new t.TokenSet;s.node.edges["*"]=u}s.str.length==1&&(u.final=!0),i.push({node:u,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)})}if(s.str.length>1){var d=s.str.charAt(0),m=s.str.charAt(1),p;m in s.node.edges?p=s.node.edges[m]:(p=new t.TokenSet,s.node.edges[m]=p),s.str.length==1&&(p.final=!0),i.push({node:p,editsRemaining:s.editsRemaining-1,str:d+s.str.slice(2)})}}}return r},t.TokenSet.fromString=function(e){for(var n=new t.TokenSet,r=n,i=0,s=e.length;i=e;n--){var r=this.uncheckedNodes[n],i=r.child.toString();i in this.minimizedNodes?r.parent.edges[r.char]=this.minimizedNodes[i]:(r.child._str=i,this.minimizedNodes[i]=r.child),this.uncheckedNodes.pop()}};t.Index=function(e){this.invertedIndex=e.invertedIndex,this.fieldVectors=e.fieldVectors,this.tokenSet=e.tokenSet,this.fields=e.fields,this.pipeline=e.pipeline},t.Index.prototype.search=function(e){return this.query(function(n){var r=new t.QueryParser(e,n);r.parse()})},t.Index.prototype.query=function(e){for(var n=new t.Query(this.fields),r=Object.create(null),i=Object.create(null),s=Object.create(null),o=Object.create(null),a=Object.create(null),l=0;l1?this._b=1:this._b=e},t.Builder.prototype.k1=function(e){this._k1=e},t.Builder.prototype.add=function(e,n){var r=e[this._ref],i=Object.keys(this._fields);this._documents[r]=n||{},this.documentCount+=1;for(var s=0;s=this.length)return t.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},t.QueryLexer.prototype.width=function(){return this.pos-this.start},t.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},t.QueryLexer.prototype.backup=function(){this.pos-=1},t.QueryLexer.prototype.acceptDigitRun=function(){var e,n;do e=this.next(),n=e.charCodeAt(0);while(n>47&&n<58);e!=t.QueryLexer.EOS&&this.backup()},t.QueryLexer.prototype.more=function(){return this.pos1&&(e.backup(),e.emit(t.QueryLexer.TERM)),e.ignore(),e.more())return t.QueryLexer.lexText},t.QueryLexer.lexEditDistance=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(t.QueryLexer.EDIT_DISTANCE),t.QueryLexer.lexText},t.QueryLexer.lexBoost=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(t.QueryLexer.BOOST),t.QueryLexer.lexText},t.QueryLexer.lexEOS=function(e){e.width()>0&&e.emit(t.QueryLexer.TERM)},t.QueryLexer.termSeparator=t.tokenizer.separator,t.QueryLexer.lexText=function(e){for(;;){var n=e.next();if(n==t.QueryLexer.EOS)return t.QueryLexer.lexEOS;if(n.charCodeAt(0)==92){e.escapeCharacter();continue}if(n==":")return t.QueryLexer.lexField;if(n=="~")return e.backup(),e.width()>0&&e.emit(t.QueryLexer.TERM),t.QueryLexer.lexEditDistance;if(n=="^")return e.backup(),e.width()>0&&e.emit(t.QueryLexer.TERM),t.QueryLexer.lexBoost;if(n=="+"&&e.width()===1||n=="-"&&e.width()===1)return e.emit(t.QueryLexer.PRESENCE),t.QueryLexer.lexText;if(n.match(t.QueryLexer.termSeparator))return t.QueryLexer.lexTerm}},t.QueryParser=function(e,n){this.lexer=new t.QueryLexer(e),this.query=n,this.currentClause={},this.lexemeIdx=0},t.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var e=t.QueryParser.parseClause;e;)e=e(this);return this.query},t.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},t.QueryParser.prototype.consumeLexeme=function(){var e=this.peekLexeme();return this.lexemeIdx+=1,e},t.QueryParser.prototype.nextClause=function(){var e=this.currentClause;this.query.clause(e),this.currentClause={}},t.QueryParser.parseClause=function(e){var n=e.peekLexeme();if(n!=null)switch(n.type){case t.QueryLexer.PRESENCE:return t.QueryParser.parsePresence;case t.QueryLexer.FIELD:return t.QueryParser.parseField;case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var r="expected either a field or a term, found "+n.type;throw n.str.length>=1&&(r+=" with value '"+n.str+"'"),new t.QueryParseError(r,n.start,n.end)}},t.QueryParser.parsePresence=function(e){var n=e.consumeLexeme();if(n!=null){switch(n.str){case"-":e.currentClause.presence=t.Query.presence.PROHIBITED;break;case"+":e.currentClause.presence=t.Query.presence.REQUIRED;break;default:var r="unrecognised presence operator'"+n.str+"'";throw new t.QueryParseError(r,n.start,n.end)}var i=e.peekLexeme();if(i==null){var r="expecting term or field, found nothing";throw new t.QueryParseError(r,n.start,n.end)}switch(i.type){case t.QueryLexer.FIELD:return t.QueryParser.parseField;case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var r="expecting term or field, found '"+i.type+"'";throw new t.QueryParseError(r,i.start,i.end)}}},t.QueryParser.parseField=function(e){var n=e.consumeLexeme();if(n!=null){if(e.query.allFields.indexOf(n.str)==-1){var r=e.query.allFields.map(function(o){return"'"+o+"'"}).join(", "),i="unrecognised field '"+n.str+"', possible fields: "+r;throw new t.QueryParseError(i,n.start,n.end)}e.currentClause.fields=[n.str];var s=e.peekLexeme();if(s==null){var i="expecting term, found nothing";throw new t.QueryParseError(i,n.start,n.end)}switch(s.type){case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var i="expecting term, found '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},t.QueryParser.parseTerm=function(e){var n=e.consumeLexeme();if(n!=null){e.currentClause.term=n.str.toLowerCase(),n.str.indexOf("*")!=-1&&(e.currentClause.usePipeline=!1);var r=e.peekLexeme();if(r==null){e.nextClause();return}switch(r.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+r.type+"'";throw new t.QueryParseError(i,r.start,r.end)}}},t.QueryParser.parseEditDistance=function(e){var n=e.consumeLexeme();if(n!=null){var r=parseInt(n.str,10);if(isNaN(r)){var i="edit distance must be numeric";throw new t.QueryParseError(i,n.start,n.end)}e.currentClause.editDistance=r;var s=e.peekLexeme();if(s==null){e.nextClause();return}switch(s.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},t.QueryParser.parseBoost=function(e){var n=e.consumeLexeme();if(n!=null){var r=parseInt(n.str,10);if(isNaN(r)){var i="boost must be numeric";throw new t.QueryParseError(i,n.start,n.end)}e.currentClause.boost=r;var s=e.peekLexeme();if(s==null){e.nextClause();return}switch(s.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},function(e,n){typeof define=="function"&&define.amd?define(n):typeof ae=="object"?le.exports=n():e.lunr=n()}(this,function(){return t})})()});var se=[];function G(t,e){se.push({selector:e,constructor:t})}var U=class{constructor(){this.alwaysVisibleMember=null;this.createComponents(document.body),this.ensureFocusedElementVisible(),this.listenForCodeCopies(),window.addEventListener("hashchange",()=>this.ensureFocusedElementVisible()),document.body.style.display||(this.ensureFocusedElementVisible(),this.updateIndexVisibility(),this.scrollToHash())}createComponents(e){se.forEach(n=>{e.querySelectorAll(n.selector).forEach(r=>{r.dataset.hasInstance||(new n.constructor({el:r,app:this}),r.dataset.hasInstance=String(!0))})})}filterChanged(){this.ensureFocusedElementVisible()}showPage(){document.body.style.display&&(document.body.style.removeProperty("display"),this.ensureFocusedElementVisible(),this.updateIndexVisibility(),this.scrollToHash())}scrollToHash(){if(location.hash){let e=document.getElementById(location.hash.substring(1));if(!e)return;e.scrollIntoView({behavior:"instant",block:"start"})}}ensureActivePageVisible(){let e=document.querySelector(".tsd-navigation .current"),n=e?.parentElement;for(;n&&!n.classList.contains(".tsd-navigation");)n instanceof HTMLDetailsElement&&(n.open=!0),n=n.parentElement;if(e&&!Ve(e)){let r=e.getBoundingClientRect().top-document.documentElement.clientHeight/4;document.querySelector(".site-menu").scrollTop=r,document.querySelector(".col-sidebar").scrollTop=r}}updateIndexVisibility(){let e=document.querySelector(".tsd-index-content"),n=e?.open;e&&(e.open=!0),document.querySelectorAll(".tsd-index-section").forEach(r=>{r.style.display="block";let i=Array.from(r.querySelectorAll(".tsd-index-link")).every(s=>s.offsetParent==null);r.style.display=i?"none":"block"}),e&&(e.open=n)}ensureFocusedElementVisible(){if(this.alwaysVisibleMember&&(this.alwaysVisibleMember.classList.remove("always-visible"),this.alwaysVisibleMember.firstElementChild.remove(),this.alwaysVisibleMember=null),!location.hash)return;let e=document.getElementById(location.hash.substring(1));if(!e)return;let n=e.parentElement;for(;n&&n.tagName!=="SECTION";)n=n.parentElement;if(!n)return;let r=n.offsetParent==null,i=n;for(;i!==document.body;)i instanceof HTMLDetailsElement&&(i.open=!0),i=i.parentElement;if(n.offsetParent==null){this.alwaysVisibleMember=n,n.classList.add("always-visible");let s=document.createElement("p");s.classList.add("warning"),s.textContent=window.translations.normally_hidden,n.prepend(s)}r&&e.scrollIntoView()}listenForCodeCopies(){document.querySelectorAll("pre > button").forEach(e=>{let n;e.addEventListener("click",()=>{e.previousElementSibling instanceof HTMLElement&&navigator.clipboard.writeText(e.previousElementSibling.innerText.trim()),e.textContent=window.translations.copied,e.classList.add("visible"),clearTimeout(n),n=setTimeout(()=>{e.classList.remove("visible"),n=setTimeout(()=>{e.textContent=window.translations.copy},100)},1e3)})})}};function Ve(t){let e=t.getBoundingClientRect(),n=Math.max(document.documentElement.clientHeight,window.innerHeight);return!(e.bottom<0||e.top-n>=0)}var oe=(t,e=100)=>{let n;return()=>{clearTimeout(n),n=setTimeout(()=>t(),e)}};var pe=Ae(ue());async function ce(t,e){if(!window.searchData)return;let n=await fetch(window.searchData),r=new Blob([await n.arrayBuffer()]).stream().pipeThrough(new DecompressionStream("gzip")),i=await new Response(r).json();t.data=i,t.index=pe.Index.load(i.index),e.classList.remove("loading"),e.classList.add("ready")}function fe(){let t=document.getElementById("tsd-search");if(!t)return;let e={base:t.dataset.base+"/"},n=document.getElementById("tsd-search-script");t.classList.add("loading"),n&&(n.addEventListener("error",()=>{t.classList.remove("loading"),t.classList.add("failure")}),n.addEventListener("load",()=>{ce(e,t)}),ce(e,t));let r=document.querySelector("#tsd-search input"),i=document.querySelector("#tsd-search .results");if(!r||!i)throw new Error("The input field or the result list wrapper was not found");i.addEventListener("mouseup",()=>{te(t)}),r.addEventListener("focus",()=>t.classList.add("has-focus")),He(t,i,r,e)}function He(t,e,n,r){n.addEventListener("input",oe(()=>{Ne(t,e,n,r)},200)),n.addEventListener("keydown",i=>{i.key=="Enter"?Be(e,t):i.key=="ArrowUp"?(de(e,n,-1),i.preventDefault()):i.key==="ArrowDown"&&(de(e,n,1),i.preventDefault())}),document.body.addEventListener("keypress",i=>{i.altKey||i.ctrlKey||i.metaKey||!n.matches(":focus")&&i.key==="/"&&(i.preventDefault(),n.focus())}),document.body.addEventListener("keyup",i=>{t.classList.contains("has-focus")&&(i.key==="Escape"||!e.matches(":focus-within")&&!n.matches(":focus"))&&(n.blur(),te(t))})}function te(t){t.classList.remove("has-focus")}function Ne(t,e,n,r){if(!r.index||!r.data)return;e.textContent="";let i=n.value.trim(),s;if(i){let o=i.split(" ").map(a=>a.length?`*${a}*`:"").join(" ");s=r.index.search(o)}else s=[];for(let o=0;oa.score-o.score);for(let o=0,a=Math.min(10,s.length);o`,d=he(l.name,i);globalThis.DEBUG_SEARCH_WEIGHTS&&(d+=` (score: ${s[o].score.toFixed(2)})`),l.parent&&(d=` ${he(l.parent,i)}.${d}`);let m=document.createElement("li");m.classList.value=l.classes??"";let p=document.createElement("a");p.href=r.base+l.url,p.innerHTML=u+d,m.append(p),p.addEventListener("focus",()=>{e.querySelector(".current")?.classList.remove("current"),m.classList.add("current")}),e.appendChild(m)}}function de(t,e,n){let r=t.querySelector(".current");if(!r)r=t.querySelector(n==1?"li:first-child":"li:last-child"),r&&r.classList.add("current");else{let i=r;if(n===1)do i=i.nextElementSibling??void 0;while(i instanceof HTMLElement&&i.offsetParent==null);else do i=i.previousElementSibling??void 0;while(i instanceof HTMLElement&&i.offsetParent==null);i?(r.classList.remove("current"),i.classList.add("current")):n===-1&&(r.classList.remove("current"),e.focus())}}function Be(t,e){let n=t.querySelector(".current");if(n||(n=t.querySelector("li:first-child")),n){let r=n.querySelector("a");r&&(window.location.href=r.href),te(e)}}function he(t,e){if(e==="")return t;let n=t.toLocaleLowerCase(),r=e.toLocaleLowerCase(),i=[],s=0,o=n.indexOf(r);for(;o!=-1;)i.push(ee(t.substring(s,o)),`${ee(t.substring(o,o+r.length))}`),s=o+r.length,o=n.indexOf(r,s);return i.push(ee(t.substring(s))),i.join("")}var je={"&":"&","<":"<",">":">","'":"'",'"':"""};function ee(t){return t.replace(/[&<>"'"]/g,e=>je[e])}var I=class{constructor(e){this.el=e.el,this.app=e.app}};var F="mousedown",ye="mousemove",N="mouseup",J={x:0,y:0},me=!1,ne=!1,qe=!1,D=!1,ve=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);document.documentElement.classList.add(ve?"is-mobile":"not-mobile");ve&&"ontouchstart"in document.documentElement&&(qe=!0,F="touchstart",ye="touchmove",N="touchend");document.addEventListener(F,t=>{ne=!0,D=!1;let e=F=="touchstart"?t.targetTouches[0]:t;J.y=e.pageY||0,J.x=e.pageX||0});document.addEventListener(ye,t=>{if(ne&&!D){let e=F=="touchstart"?t.targetTouches[0]:t,n=J.x-(e.pageX||0),r=J.y-(e.pageY||0);D=Math.sqrt(n*n+r*r)>10}});document.addEventListener(N,()=>{ne=!1});document.addEventListener("click",t=>{me&&(t.preventDefault(),t.stopImmediatePropagation(),me=!1)});var X=class extends I{constructor(e){super(e),this.className=this.el.dataset.toggle||"",this.el.addEventListener(N,n=>this.onPointerUp(n)),this.el.addEventListener("click",n=>n.preventDefault()),document.addEventListener(F,n=>this.onDocumentPointerDown(n)),document.addEventListener(N,n=>this.onDocumentPointerUp(n))}setActive(e){if(this.active==e)return;this.active=e,document.documentElement.classList.toggle("has-"+this.className,e),this.el.classList.toggle("active",e);let n=(this.active?"to-has-":"from-has-")+this.className;document.documentElement.classList.add(n),setTimeout(()=>document.documentElement.classList.remove(n),500)}onPointerUp(e){D||(this.setActive(!0),e.preventDefault())}onDocumentPointerDown(e){if(this.active){if(e.target.closest(".col-sidebar, .tsd-filter-group"))return;this.setActive(!1)}}onDocumentPointerUp(e){if(!D&&this.active&&e.target.closest(".col-sidebar")){let n=e.target.closest("a");if(n){let r=window.location.href;r.indexOf("#")!=-1&&(r=r.substring(0,r.indexOf("#"))),n.href.substring(0,r.length)==r&&setTimeout(()=>this.setActive(!1),250)}}}};var re;try{re=localStorage}catch{re={getItem(){return null},setItem(){}}}var Q=re;var ge=document.head.appendChild(document.createElement("style"));ge.dataset.for="filters";var Y=class extends I{constructor(e){super(e),this.key=`filter-${this.el.name}`,this.value=this.el.checked,this.el.addEventListener("change",()=>{this.setLocalStorage(this.el.checked)}),this.setLocalStorage(this.fromLocalStorage()),ge.innerHTML+=`html:not(.${this.key}) .tsd-is-${this.el.name} { display: none; } -`,this.app.updateIndexVisibility()}fromLocalStorage(){let e=Q.getItem(this.key);return e?e==="true":this.el.checked}setLocalStorage(e){Q.setItem(this.key,e.toString()),this.value=e,this.handleValueChange()}handleValueChange(){this.el.checked=this.value,document.documentElement.classList.toggle(this.key,this.value),this.app.filterChanged(),this.app.updateIndexVisibility()}};var Z=class extends I{constructor(e){super(e),this.summary=this.el.querySelector(".tsd-accordion-summary"),this.icon=this.summary.querySelector("svg"),this.key=`tsd-accordion-${this.summary.dataset.key??this.summary.textContent.trim().replace(/\s+/g,"-").toLowerCase()}`;let n=Q.getItem(this.key);this.el.open=n?n==="true":this.el.open,this.el.addEventListener("toggle",()=>this.update());let r=this.summary.querySelector("a");r&&r.addEventListener("click",()=>{location.assign(r.href)}),this.update()}update(){this.icon.style.transform=`rotate(${this.el.open?0:-90}deg)`,Q.setItem(this.key,this.el.open.toString())}};function Ee(t){let e=Q.getItem("tsd-theme")||"os";t.value=e,xe(e),t.addEventListener("change",()=>{Q.setItem("tsd-theme",t.value),xe(t.value)})}function xe(t){document.documentElement.dataset.theme=t}var K;function we(){let t=document.getElementById("tsd-nav-script");t&&(t.addEventListener("load",Le),Le())}async function Le(){let t=document.getElementById("tsd-nav-container");if(!t||!window.navigationData)return;let n=await(await fetch(window.navigationData)).arrayBuffer(),r=new Blob([n]).stream().pipeThrough(new DecompressionStream("gzip")),i=await new Response(r).json();K=t.dataset.base,K.endsWith("/")||(K+="/"),t.innerHTML="";for(let s of i)Se(s,t,[]);window.app.createComponents(t),window.app.showPage(),window.app.ensureActivePageVisible()}function Se(t,e,n){let r=e.appendChild(document.createElement("li"));if(t.children){let i=[...n,t.text],s=r.appendChild(document.createElement("details"));s.className=t.class?`${t.class} tsd-accordion`:"tsd-accordion";let o=s.appendChild(document.createElement("summary"));o.className="tsd-accordion-summary",o.dataset.key=i.join("$"),o.innerHTML='',be(t,o);let a=s.appendChild(document.createElement("div"));a.className="tsd-accordion-details";let l=a.appendChild(document.createElement("ul"));l.className="tsd-nested-navigation";for(let u of t.children)Se(u,l,i)}else be(t,r,t.class)}function be(t,e,n){if(t.path){let r=e.appendChild(document.createElement("a"));r.href=K+t.path,n&&(r.className=n),location.pathname===r.pathname&&r.classList.add("current"),t.kind&&(r.innerHTML=``),r.appendChild(document.createElement("span")).textContent=t.text}else e.appendChild(document.createElement("span")).textContent=t.text}G(X,"a[data-toggle]");G(Z,".tsd-accordion");G(Y,".tsd-filter-item input[type=checkbox]");var Te=document.getElementById("tsd-theme");Te&&Ee(Te);var $e=new U;Object.defineProperty(window,"app",{value:$e});fe();we();})(); +`,this.app.updateIndexVisibility()}fromLocalStorage(){let e=Q.getItem(this.key);return e?e==="true":this.el.checked}setLocalStorage(e){Q.setItem(this.key,e.toString()),this.value=e,this.handleValueChange()}handleValueChange(){this.el.checked=this.value,document.documentElement.classList.toggle(this.key,this.value),this.app.filterChanged(),this.app.updateIndexVisibility()}};var Z=class extends I{constructor(e){super(e),this.summary=this.el.querySelector(".tsd-accordion-summary"),this.icon=this.summary.querySelector("svg"),this.key=`tsd-accordion-${this.summary.dataset.key??this.summary.textContent.trim().replace(/\s+/g,"-").toLowerCase()}`;let n=Q.getItem(this.key);this.el.open=n?n==="true":this.el.open,this.el.addEventListener("toggle",()=>this.update());let r=this.summary.querySelector("a");r&&r.addEventListener("click",()=>{location.assign(r.href)}),this.update()}update(){this.icon.style.transform=`rotate(${this.el.open?0:-90}deg)`,Q.setItem(this.key,this.el.open.toString())}};function Ee(t){let e=Q.getItem("tsd-theme")||"os";t.value=e,xe(e),t.addEventListener("change",()=>{Q.setItem("tsd-theme",t.value),xe(t.value)})}function xe(t){document.documentElement.dataset.theme=t}var K;function we(){let t=document.getElementById("tsd-nav-script");t&&(t.addEventListener("load",Le),Le())}async function Le(){let t=document.getElementById("tsd-nav-container");if(!t||!window.navigationData)return;let n=await(await fetch(window.navigationData)).arrayBuffer(),r=new Blob([n]).stream().pipeThrough(new DecompressionStream("gzip")),i=await new Response(r).json();K=t.dataset.base,K.endsWith("/")||(K+="/"),t.innerHTML="";for(let s of i)Se(s,t,[]);window.app.createComponents(t),window.app.showPage(),window.app.ensureActivePageVisible()}function Se(t,e,n){let r=e.appendChild(document.createElement("li"));if(t.children){let i=[...n,t.text],s=r.appendChild(document.createElement("details"));s.className=t.class?`${t.class} tsd-accordion`:"tsd-accordion";let o=s.appendChild(document.createElement("summary"));o.className="tsd-accordion-summary",o.dataset.key=i.join("$"),o.innerHTML='',be(t,o);let a=s.appendChild(document.createElement("div"));a.className="tsd-accordion-details";let l=a.appendChild(document.createElement("ul"));l.className="tsd-nested-navigation";for(let u of t.children)Se(u,l,i)}else be(t,r,t.class)}function be(t,e,n){if(t.path){let r=e.appendChild(document.createElement("a"));r.href=K+t.path,n&&(r.className=n),location.pathname===r.pathname&&!r.href.includes("#")&&r.classList.add("current"),t.kind&&(r.innerHTML=``),r.appendChild(document.createElement("span")).textContent=t.text}else e.appendChild(document.createElement("span")).textContent=t.text}G(X,"a[data-toggle]");G(Z,".tsd-accordion");G(Y,".tsd-filter-item input[type=checkbox]");var Te=document.getElementById("tsd-theme");Te&&Ee(Te);var $e=new U;Object.defineProperty(window,"app",{value:$e});fe();we();})(); /*! Bundled license information: lunr/lunr.js: diff --git a/docs/functions/addMahalanobisDistance.html b/docs/functions/addMahalanobisDistance.html index b749da72..17ecd254 100644 --- a/docs/functions/addMahalanobisDistance.html +++ b/docs/functions/addMahalanobisDistance.html @@ -1,6 +1,6 @@ -addMahalanobisDistance | Journalism - v1.15.3

Function addMahalanobisDistance

  • Computes the Mahalanobis distance from an origin object for each object in an array. The keys in the origin object are the dimensions considered (tested up to four dimensions but should work for more in theory). The function adds the key mahaDist in each object in the original array.

    +addMahalanobisDistance | Journalism - v1.15.4

    Function addMahalanobisDistance

    • Computes the Mahalanobis distance from an origin object for each object in an array. The keys in the origin object are the dimensions considered (tested up to four dimensions but should work for more in theory). The function adds the key mahaDist in each object in the original array.

      If you pass the option { similarity: true }, it will add another key similarity which goes from 1 to 0. The closer similarity is to 1, the closer the item is to the origin. You can also pass a precomputed matrix in options if needed: { matrix : precomputedMatrix }.

      Parameters

      • origin: Record<string, number>
      • data: Record<string, unknown>[]
      • options: {
            matrix?: number[][];
            similarity?: boolean;
        } = {}
        • Optionalmatrix?: number[][]
        • Optionalsimilarity?: boolean

      Returns Record<string, unknown>[]

      // Wines
      const data = [
      {'fixed acidity': 6.5, 'alcohol' : 11, ... },
      {'fixed acidity': 7.1, 'alcohol' : 12.2, ... },
      {'fixed acidity': 6.3, 'alcohol' : 10.5, ... }
      ]

      // We want the distance from this wine. All the keys in the origin will be used as variables. They need to be present in the data, of course.
      const origin = {'fixed acidity': 7.2, 'alcohol' : 11.3 }

      addMahalanobisDistance(origin, data)

      // We now have mahaDist in the data.
      data.sort((a, b) => a.mahaDist - b.mahaDist)

      // And data looks like this.
      //[
      // { 'fixed acidity': 7.2, alcohol: 11.3, mahaDist: 0 },
      // { 'fixed acidity': 7.5, alcohol: 10.5, mahaDist: 0.939 },
      // { 'fixed acidity': 7.3, alcohol: 11.4, mahaDist: 1.263 },
      // { 'fixed acidity': 6.5, alcohol: 13, mahaDist: 2.079 },
      // { 'fixed acidity': 7.1, alcohol: 12.2, mahaDist: 2.411 }
      //]

      // You can also pass the option similarity if you want.
      addMahalanobisDistance(origin, data, { similarity: true })

      // The data will have a similarity key going from 0 to 1.
      // [
      // { "fixed acidity": 7.2, alcohol: 11.3, mahaDist: 0, similarity: 1 },
      // { "fixed acidity": 7.5, alcohol: 10.5, mahaDist: 0.939, similarity: 0.611 },
      // { "fixed acidity": 7.3, alcohol: 11.4, mahaDist: 1.263, similarity: 0.476 },
      // { "fixed acidity": 6.5, alcohol: 13, mahaDist: 2.079, similarity: 0.138 },
      // { "fixed acidity": 7.1, alcohol: 12.2, mahaDist: 2.412, similarity: 0 }
      // ]
      -
    +
diff --git a/docs/functions/addZscore.html b/docs/functions/addZscore.html index c93bbc02..cf339fb1 100644 --- a/docs/functions/addZscore.html +++ b/docs/functions/addZscore.html @@ -1,5 +1,5 @@ -addZScore | Journalism - v1.15.3

Function addZScore

  • Computes the Z-Score for a given variable in an array of objects. By default, the function adds a new key zScore in each object, but you can change it by passing this option as the last parameter { newKey: "myNewKey" }.

    +addZScore | Journalism - v1.15.4

    Function addZScore

    • Computes the Z-Score for a given variable in an array of objects. By default, the function adds a new key zScore in each object, but you can change it by passing this option as the last parameter { newKey: "myNewKey" }.

      Parameters

      • data: Record<string, unknown>[]
      • variable: string
      • options: {
            newKey?: string;
        } = {}
        • OptionalnewKey?: string

      Returns Record<string, unknown>[]

      // Let's say we have a data set like this.
      const data = [
      { grade: 1 },
      { grade: 4 },
      { grade: 7 },
      { grade: 2 },
      { grade: 6 },
      ]

      // We compute the Z-Score for the variable grade.
      addZScore(data, "grade")

      // We now have the key zScore in the data.
      // [
      // { grade: 1, zScore: -1.3155870289605438 },
      // { grade: 4, zScore: 0 },
      // { grade: 7, zScore: 1.3155870289605438 },
      // { grade: 2, zScore: -0.8770580193070292 },
      // { grade: 6, zScore: 0.8770580193070292 },
      // ]

      // If you want a specific new key, use the options.
      addZScore(data, "grade", { newKey: "zScoreGrade"})

      // We now have the key zScoreGrade in the data.
      // [
      // { grade: 1, zScoreGrade: -1.3155870289605438 },
      // { grade: 4, zScoreGrade: 0 },
      // { grade: 7, zScoreGrade: 1.3155870289605438 },
      // { grade: 2, zScoreGrade: -0.8770580193070292 },
      // { grade: 6, zScoreGrade: 0.8770580193070292 },
      // ]
      -
    +
diff --git a/docs/functions/adjustToInflation.html b/docs/functions/adjustToInflation.html index 832546ec..51c82a8b 100644 --- a/docs/functions/adjustToInflation.html +++ b/docs/functions/adjustToInflation.html @@ -1,5 +1,5 @@ -adjustToInflation | Journalism - v1.15.3

Function adjustToInflation

  • Compute the adjusted to inflation amount of money, based on the Consumer Price Index. The options (last parameter) are optional.

    +adjustToInflation | Journalism - v1.15.4

    Function adjustToInflation

    • Compute the adjusted to inflation amount of money, based on the Consumer Price Index. The options (last parameter) are optional.

      // $100 in 1914 (CPI of 6.0) to 2023 value (CPI of 156.4)
      const adjustedAmount = adjustToInflation(100, 6.0, 156.4, { decimals: 0 })
      // returns 2607 dollars
      -

      Parameters

      • amount: number
      • amountCPI: number
      • targetCPI: number
      • options: {
            decimals?: number;
        } = {}
        • Optionaldecimals?: number

      Returns number

    +

    Parameters

    • amount: number
    • amountCPI: number
    • targetCPI: number
    • options: {
          decimals?: number;
      } = {}
      • Optionaldecimals?: number

    Returns number

diff --git a/docs/functions/arraysToData.html b/docs/functions/arraysToData.html index 5e383dfc..a3da1376 100644 --- a/docs/functions/arraysToData.html +++ b/docs/functions/arraysToData.html @@ -1,4 +1,4 @@ -arraysToData | Journalism - v1.15.3

Function arraysToData

  • Returns an array of objects from an object made of arrays.

    +arraysToData | Journalism - v1.15.4

    Function arraysToData

    • Returns an array of objects from an object made of arrays.

      For example, this data...

      {
      keyA: ["a", "b", "c"],
      keyB: [1, 2, 3],
      }
      @@ -7,4 +7,4 @@
      [
      { keyA: "a", keyB: 1 },
      { keyA: "b", keyB: 2 },
      { keyA: "c", keyB: 3 },
      ]
      -

      Parameters

      • data: {
            [key: string]: unknown[];
        }
        • [key: string]: unknown[]

      Returns {
          [key: string]: unknown;
      }[]

    +

    Parameters

    • data: {
          [key: string]: unknown[];
      }
      • [key: string]: unknown[]

    Returns {
        [key: string]: unknown;
    }[]

diff --git a/docs/functions/camelCase.html b/docs/functions/camelCase.html index 24ad89b3..ac2828f4 100644 --- a/docs/functions/camelCase.html +++ b/docs/functions/camelCase.html @@ -1,5 +1,5 @@ -camelCase | Journalism - v1.15.3

Function camelCase

  • Formats a string to camel case.

    +camelCase | Journalism - v1.15.4

    Function camelCase

    • Formats a string to camel case.

      // Returns journalismIsAwesome
      const text = camelCase("Journalism is awesome")
      -

      Parameters

      • input: string

      Returns string

    +

    Parameters

    • input: string

    Returns string

diff --git a/docs/functions/capitalize.html b/docs/functions/capitalize.html index 1f2ceb62..e4110f3e 100644 --- a/docs/functions/capitalize.html +++ b/docs/functions/capitalize.html @@ -1,5 +1,5 @@ -capitalize | Journalism - v1.15.3

Function capitalize

  • Capitalizes the first character of a string.

    +capitalize | Journalism - v1.15.4

    Function capitalize

    • Capitalizes the first character of a string.

      // Returns 'Journalism'.
      const text = capitalize('journalism')
      -

      Parameters

      • string: string

      Returns string

    +

    Parameters

    • string: string

    Returns string

diff --git a/docs/functions/createDirectory.html b/docs/functions/createDirectory.html index d184dd7c..0568cbaf 100644 --- a/docs/functions/createDirectory.html +++ b/docs/functions/createDirectory.html @@ -1,5 +1,5 @@ -createDirectory | Journalism - v1.15.3

Function createDirectory

  • Creates folders recursively if they don't exist.

    +createDirectory | Journalism - v1.15.4

    Function createDirectory

    • Creates folders recursively if they don't exist.

      // Creates folders if they don't exist
      createDirectory("./data/json")

      // This will give the same result. A file with an extension at the end of the path will be ignored.
      createDirectory("./data/json/items.json")
      -

      Parameters

      • path: string

      Returns void

    +

    Parameters

    • path: string

    Returns void

diff --git a/docs/functions/dataAsCsv.html b/docs/functions/dataAsCsv.html index b913d6d6..36da53f9 100644 --- a/docs/functions/dataAsCsv.html +++ b/docs/functions/dataAsCsv.html @@ -1,5 +1,5 @@ -dataAsCsv | Journalism - v1.15.3

Function dataAsCsv

  • Convert an array of objects into CSV format.

    +dataAsCsv | Journalism - v1.15.4

    Function dataAsCsv

    • Convert an array of objects into CSV format.

      const data = [
      { firstName: "Graeme", lastName: "Bruce" },
      { firstName: "Nael", lastName: "Shiab" },
      ]

      const csv = dataAsCsv(data)
      // Returns "firstName,lastName\nGraeme,Bruce\nNael,Shiab"
      -

      Parameters

      • arrayOfObjects: {
            [key: string]: unknown;
        }[]

      Returns string

    +

    Parameters

    • arrayOfObjects: {
          [key: string]: unknown;
      }[]

    Returns string

diff --git a/docs/functions/dataToArrays.html b/docs/functions/dataToArrays.html index 03afe960..5a0a63dc 100644 --- a/docs/functions/dataToArrays.html +++ b/docs/functions/dataToArrays.html @@ -1,4 +1,4 @@ -dataToArrays | Journalism - v1.15.3

Function dataToArrays

  • Returns an object made of arrays from an array of objects.

    +dataToArrays | Journalism - v1.15.4

    Function dataToArrays

    • Returns an object made of arrays from an array of objects.

      For example, this data...

      [
      { keyA: "a", keyB: 1 },
      { keyA: "b", keyB: 2 },
      { keyA: "c", keyB: 3 },
      ]
      @@ -7,4 +7,4 @@
      {
      keyA: ["a", "b", "c"],
      keyB: [1, 2, 3],
      }
      -

      Parameters

      • data: {
            [key: string]: unknown;
        }[]

      Returns {
          [key: string]: unknown[];
      }

      • [key: string]: unknown[]
    +

    Parameters

    • data: {
          [key: string]: unknown;
      }[]

    Returns {
        [key: string]: unknown[];
    }

    • [key: string]: unknown[]
diff --git a/docs/functions/distance.html b/docs/functions/distance.html index e11019f3..73dd7369 100644 --- a/docs/functions/distance.html +++ b/docs/functions/distance.html @@ -1,5 +1,5 @@ -distance | Journalism - v1.15.3

Function distance

  • Compute the distance in kilometres based on longitude and latitude. The options (last parameter) are optional.

    +distance | Journalism - v1.15.4

    Function distance

    • Compute the distance in kilometres based on longitude and latitude. The options (last parameter) are optional.

      const distance = distance(-73.66, 45.51, -79.43, 43.66, { decimals: 0 })
      // returns 501
      -

      Parameters

      • lon1: number
      • lat1: number
      • lon2: number
      • lat2: number
      • options: {
            decimals?: number;
        } = {}
        • Optionaldecimals?: number

      Returns number

    +

    Parameters

    • lon1: number
    • lat1: number
    • lon2: number
    • lat2: number
    • options: {
          decimals?: number;
      } = {}
      • Optionaldecimals?: number

    Returns number

diff --git a/docs/functions/downloadFile.html b/docs/functions/downloadFile.html index 23391435..40bccf7c 100644 --- a/docs/functions/downloadFile.html +++ b/docs/functions/downloadFile.html @@ -1,5 +1,5 @@ -downloadFile | Journalism - v1.15.3

Function downloadFile

  • Downloads a file.

    +downloadFile | Journalism - v1.15.4

    Function downloadFile

    • Downloads a file.

      await dowloadFile("http://some-website.com/data.csv", "./downloads/data.csv" )
       
      -

      Parameters

      • url: string
      • filePath: string

      Returns Promise<void>

    +

    Parameters

    • url: string
    • filePath: string

    Returns Promise<void>

diff --git a/docs/functions/formatDate.html b/docs/functions/formatDate.html index dfa56cce..3120ae65 100644 --- a/docs/functions/formatDate.html +++ b/docs/functions/formatDate.html @@ -1,6 +1,6 @@ -formatDate | Journalism - v1.15.3

Function formatDate

  • Format a Date as a string with a specific format and a specific style. To format as UTC Date, set the utc option to true.

    +formatDate | Journalism - v1.15.4

    Function formatDate

    • Format a Date as a string with a specific format and a specific style. To format as UTC Date, set the utc option to true.

      const date = new Date("2023-01-01T01:35:00.000Z")
      const string = formatDate(date, "Month DD, YYYY, at HH:MM period", { utc: true, abbreviations: true })
      // returns "Jan. 1, 2023, at 1:35 p.m."

      Options can be passed as the last parameter. Pass {style: "rc"} to parse dates in French.

      -

      Parameters

      • date: Date
      • format:
            | "YYYY-MM-DD"
            | "YYYY-MM-DD HH:MM:SS TZ"
            | "DayOfWeek, Month Day"
            | "Month DD"
            | "Month DD, HH:MM period"
            | "Month DD, HH:MM period TZ"
            | "DayOfWeek, HH:MM period"
            | "DayOfWeek, HH:MM period TZ"
            | "Month DD, YYYY"
            | "Month DD, YYYY, at HH:MM period"
            | "Month DD, YYYY, at HH:MM period TZ"
            | "DayOfWeek"
            | "Month"
            | "YYYY"
            | "MM"
            | "DD"
            | "HH:MM period"
            | "HH:MM period TZ"
      • options: {
            abbreviations?: boolean;
            noZeroPadding?: boolean;
            style?: "cbc" | "rc";
            timeZone?:
                | "Canada/Atlantic"
                | "Canada/Central"
                | "Canada/Eastern"
                | "Canada/Mountain"
                | "Canada/Newfoundland"
                | "Canada/Pacific"
                | "Canada/Saskatchewan"
                | "Canada/Yukon";
            utc?: boolean;
        } = {}
        • Optionalabbreviations?: boolean
        • OptionalnoZeroPadding?: boolean
        • Optionalstyle?: "cbc" | "rc"
        • OptionaltimeZone?:
              | "Canada/Atlantic"
              | "Canada/Central"
              | "Canada/Eastern"
              | "Canada/Mountain"
              | "Canada/Newfoundland"
              | "Canada/Pacific"
              | "Canada/Saskatchewan"
              | "Canada/Yukon"
        • Optionalutc?: boolean

      Returns string

    +

    Parameters

    • date: Date
    • format:
          | "YYYY-MM-DD"
          | "YYYY-MM-DD HH:MM:SS TZ"
          | "DayOfWeek, Month Day"
          | "Month DD"
          | "Month DD, HH:MM period"
          | "Month DD, HH:MM period TZ"
          | "DayOfWeek, HH:MM period"
          | "DayOfWeek, HH:MM period TZ"
          | "Month DD, YYYY"
          | "Month DD, YYYY, at HH:MM period"
          | "Month DD, YYYY, at HH:MM period TZ"
          | "DayOfWeek"
          | "Month"
          | "YYYY"
          | "MM"
          | "DD"
          | "HH:MM period"
          | "HH:MM period TZ"
    • options: {
          abbreviations?: boolean;
          noZeroPadding?: boolean;
          style?: "cbc" | "rc";
          timeZone?:
              | "Canada/Atlantic"
              | "Canada/Central"
              | "Canada/Eastern"
              | "Canada/Mountain"
              | "Canada/Newfoundland"
              | "Canada/Pacific"
              | "Canada/Saskatchewan"
              | "Canada/Yukon";
          utc?: boolean;
      } = {}
      • Optionalabbreviations?: boolean
      • OptionalnoZeroPadding?: boolean
      • Optionalstyle?: "cbc" | "rc"
      • OptionaltimeZone?:
            | "Canada/Atlantic"
            | "Canada/Central"
            | "Canada/Eastern"
            | "Canada/Mountain"
            | "Canada/Newfoundland"
            | "Canada/Pacific"
            | "Canada/Saskatchewan"
            | "Canada/Yukon"
      • Optionalutc?: boolean

    Returns string

diff --git a/docs/functions/formatNumber.html b/docs/functions/formatNumber.html index 5e6313b8..1ce4213d 100644 --- a/docs/functions/formatNumber.html +++ b/docs/functions/formatNumber.html @@ -1,4 +1,4 @@ -formatNumber | Journalism - v1.15.3

Function formatNumber

  • Format a number with a specific style.

    +formatNumber | Journalism - v1.15.4

    Function formatNumber

    • Format a number with a specific style.

      const string = formatNumber(1234.567, { sign: true, round: true })
      // returns "+1,235"
      @@ -14,4 +14,4 @@
    • prefix: a string to add before the number, "$" for example
    • suffix: a string to add after the number, "%" for example
    -

    Parameters

    • number: number
    • options: {
          decimals?: number;
          fixed?: boolean;
          nearestInteger?: number;
          prefix?: string;
          round?: boolean;
          sign?: boolean;
          significantDigits?: number;
          style?: "cbc" | "rc";
          suffix?: string;
      } = {}
      • Optionaldecimals?: number
      • Optionalfixed?: boolean
      • OptionalnearestInteger?: number
      • Optionalprefix?: string
      • Optionalround?: boolean
      • Optionalsign?: boolean
      • OptionalsignificantDigits?: number
      • Optionalstyle?: "cbc" | "rc"
      • Optionalsuffix?: string

    Returns string

+

Parameters

  • number: number
  • options: {
        decimals?: number;
        fixed?: boolean;
        nearestInteger?: number;
        prefix?: string;
        round?: boolean;
        sign?: boolean;
        significantDigits?: number;
        style?: "cbc" | "rc";
        suffix?: string;
    } = {}
    • Optionaldecimals?: number
    • Optionalfixed?: boolean
    • OptionalnearestInteger?: number
    • Optionalprefix?: string
    • Optionalround?: boolean
    • Optionalsign?: boolean
    • OptionalsignificantDigits?: number
    • Optionalstyle?: "cbc" | "rc"
    • Optionalsuffix?: string

Returns string

diff --git a/docs/functions/geoTo3D.html b/docs/functions/geoTo3D.html index 6120bbff..f6732642 100644 --- a/docs/functions/geoTo3D.html +++ b/docs/functions/geoTo3D.html @@ -1,6 +1,6 @@ -geoTo3D | Journalism - v1.15.3

Function geoTo3D

  • Convert longitude and latitude to x,y,z coordinates based on a given radius. The options (last parameter) are optional.

    +geoTo3D | Journalism - v1.15.4

    Function geoTo3D

    • Convert longitude and latitude to x,y,z coordinates based on a given radius. The options (last parameter) are optional.

      const coords = geoTo3D(-73.5674, 45.5019, 1, { decimals: 2})
      // returns { x: -0.67, y: 0.71, z: 0.2 }

      You can pass { toArray: true } to return an array instead of an object.

      -

      Parameters

      • lon: number
      • lat: number
      • radius: number
      • options: {
            decimals?: number;
            toArray?: boolean;
        } = {}
        • Optionaldecimals?: number
        • OptionaltoArray?: boolean

      Returns {
          x: number;
          y: number;
          z: number;
      } | [number, number, number]

    +

    Parameters

    • lon: number
    • lat: number
    • radius: number
    • options: {
          decimals?: number;
          toArray?: boolean;
      } = {}
      • Optionaldecimals?: number
      • OptionaltoArray?: boolean

    Returns {
        x: number;
        y: number;
        z: number;
    } | [number, number, number]

diff --git a/docs/functions/getClosest.html b/docs/functions/getClosest.html index b6b1453d..05b9ff39 100644 --- a/docs/functions/getClosest.html +++ b/docs/functions/getClosest.html @@ -1,5 +1,5 @@ -getClosest | Journalism - v1.15.3

Function getClosest

  • Return the closest item of a list based on longitude and latitude. The options (last parameter) are optional. If addDistance is true and geoItems have a properties key, the distance will be added to the properties.

    +getClosest | Journalism - v1.15.4

    Function getClosest

    • Return the closest item of a list based on longitude and latitude. The options (last parameter) are optional. If addDistance is true and geoItems have a properties key, the distance will be added to the properties.

      const geoItems = [
      {name: "Montreal", lon: -73.66, lat: 45.51 },
      {name: "Toronto", lon: -79.43, lat: 43.66 },
      ]
      const ottawa = {lat: 45.37, lon: -75.71}
      const closest = getClosest(
      ottawa.lon,
      ottawa.lat,
      geoItems,
      d => d.lon,
      d => d.lat,
      { addDistance: true, decimals: 3 }
      )
      // return { name: "Montreal", lon: -73.66, lat: 45.51, distance: 160.694 }
      -

      Parameters

      • lon: number
      • lat: number
      • geoItems: unknown[]
      • getItemLon: ((d: unknown) => number)
          • (d): number
          • Parameters

            • d: unknown

            Returns number

      • getItemLat: ((d: unknown) => number)
          • (d): number
          • Parameters

            • d: unknown

            Returns number

      • options: {
            addDistance?: boolean;
            decimals?: number;
        } = {}
        • OptionaladdDistance?: boolean
        • Optionaldecimals?: number

      Returns {
          distance?: number;
          properties?: {
              distance?: number;
          };
      }

      • Optionaldistance?: number
      • Optionalproperties?: {
            distance?: number;
        }
        • Optionaldistance?: number
    +

    Parameters

    • lon: number
    • lat: number
    • geoItems: unknown[]
    • getItemLon: ((d: unknown) => number)
        • (d): number
        • Parameters

          • d: unknown

          Returns number

    • getItemLat: ((d: unknown) => number)
        • (d): number
        • Parameters

          • d: unknown

          Returns number

    • options: {
          addDistance?: boolean;
          decimals?: number;
      } = {}
      • OptionaladdDistance?: boolean
      • Optionaldecimals?: number

    Returns {
        distance?: number;
        properties?: {
            distance?: number;
        };
    }

    • Optionaldistance?: number
    • Optionalproperties?: {
          distance?: number;
      }
      • Optionaldistance?: number
diff --git a/docs/functions/getCovarianceMatrix.html b/docs/functions/getCovarianceMatrix.html index 46e81c9e..80eddfce 100644 --- a/docs/functions/getCovarianceMatrix.html +++ b/docs/functions/getCovarianceMatrix.html @@ -1,2 +1,2 @@ -getCovarianceMatrix | Journalism - v1.15.3

Function getCovarianceMatrix

  • Computes the covariance matrix, with an option to invert it.

    -

    Parameters

    • data: number[][]
    • options: {
          invert?: boolean;
      } = {}
      • Optionalinvert?: boolean

    Returns number[][]

+getCovarianceMatrix | Journalism - v1.15.4

Function getCovarianceMatrix

  • Computes the covariance matrix, with an option to invert it.

    +

    Parameters

    • data: number[][]
    • options: {
          invert?: boolean;
      } = {}
      • Optionalinvert?: boolean

    Returns number[][]

diff --git a/docs/functions/getGeoTiffDetails.html b/docs/functions/getGeoTiffDetails.html index 9cec4b02..6da6638b 100644 --- a/docs/functions/getGeoTiffDetails.html +++ b/docs/functions/getGeoTiffDetails.html @@ -1,5 +1,5 @@ -getGeoTiffDetails | Journalism - v1.15.3

Function getGeoTiffDetails

  • Extracts detailed informations from a geoTIFF that can be used with the getGeoTiffValues function. Just for NodeJS and similar runtimes.

    +getGeoTiffDetails | Journalism - v1.15.4

    Function getGeoTiffDetails

    • Extracts detailed informations from a geoTIFF that can be used with the getGeoTiffValues function. Just for NodeJS and similar runtimes.

      const geoTiffDetails = await getGeoTiffDetails("./some-file.tif")
      const value = await getGeoTiffValues(45.50, -73.57, geoTiffDetails)
      -

      Parameters

      • path: string

      Returns Promise<{
          bbox: number[];
          bboxHeight: number;
          bboxWidth: number;
          image: GeoTIFFImage;
          pixelHeight: number;
          pixelWidth: number;
      }>

    +

    Parameters

    • path: string

    Returns Promise<{
        bbox: number[];
        bboxHeight: number;
        bboxWidth: number;
        image: GeoTIFFImage;
        pixelHeight: number;
        pixelWidth: number;
    }>

diff --git a/docs/functions/getGeoTiffValues.html b/docs/functions/getGeoTiffValues.html index ec5ad8b8..4d28d608 100644 --- a/docs/functions/getGeoTiffValues.html +++ b/docs/functions/getGeoTiffValues.html @@ -1,5 +1,5 @@ -getGeoTiffValues | Journalism - v1.15.3

Function getGeoTiffValues

  • Extracts values at specific lat/lon coordinates from a geotiff. Works with the values returned by the getGeoTiffDetails function.

    +getGeoTiffValues | Journalism - v1.15.4

    Function getGeoTiffValues

    • Extracts values at specific lat/lon coordinates from a geotiff. Works with the values returned by the getGeoTiffDetails function.

      const geoTiffDetails = await getGeoTiffDetails("./some-file.tif")
      const value = await getGeoTiffValues(45.50, -73.57, geoTiffDetails)
      -

      Parameters

      • lat: number
      • lon: number
      • __namedParameters: {
            bbox: number[];
            bboxHeight: number;
            bboxWidth: number;
            image: GeoTIFFImage;
            pixelHeight: number;
            pixelWidth: number;
        }
        • bbox: number[]
        • bboxHeight: number
        • bboxWidth: number
        • image: GeoTIFFImage
        • pixelHeight: number
        • pixelWidth: number

      Returns Promise<TypedArray>

    +

    Parameters

    • lat: number
    • lon: number
    • __namedParameters: {
          bbox: number[];
          bboxHeight: number;
          bboxWidth: number;
          image: GeoTIFFImage;
          pixelHeight: number;
          pixelWidth: number;
      }
      • bbox: number[]
      • bboxHeight: number
      • bboxWidth: number
      • image: GeoTIFFImage
      • pixelHeight: number
      • pixelWidth: number

    Returns Promise<TypedArray>

diff --git a/docs/functions/getHtmlTable.html b/docs/functions/getHtmlTable.html index ae927de3..fbc3c652 100644 --- a/docs/functions/getHtmlTable.html +++ b/docs/functions/getHtmlTable.html @@ -1,5 +1,5 @@ -getHtmlTable | Journalism - v1.15.3

Function getHtmlTable

  • Returns the data from an HTML table as an array of objects. The first parameter is an url. The second parameter is an optional object specifying a css selector and/or an index.

    +getHtmlTable | Journalism - v1.15.4

    Function getHtmlTable

    • Returns the data from an HTML table as an array of objects. The first parameter is an url. The second parameter is an optional object specifying a css selector and/or an index.

      // This would parse the data from the fourth
      // table with the class name data-table.
      const data = await getHtmlTable("your-url-here", {
      selector: ".data-table",
      index: 3
      })
      -

      Parameters

      • url: string
      • options: {
            index?: number;
            selector?: string;
        } = {}
        • Optionalindex?: number
        • Optionalselector?: string

      Returns Promise<DSVRowArray<string>>

    +

    Parameters

    • url: string
    • options: {
          index?: number;
          selector?: string;
      } = {}
      • Optionalindex?: number
      • Optionalselector?: string

    Returns Promise<DSVRowArray<string>>

diff --git a/docs/functions/getHumidex.html b/docs/functions/getHumidex.html index 107c62eb..c4956fc1 100644 --- a/docs/functions/getHumidex.html +++ b/docs/functions/getHumidex.html @@ -1,7 +1,7 @@ -getHumidex | Journalism - v1.15.3

Function getHumidex

  • Calculate Humidex Factor in Celsius given the temperature in Celsius and humidity percentage. +getHumidex | Journalism - v1.15.4

    Function getHumidex

    • Calculate Humidex Factor in Celsius given the temperature in Celsius and humidity percentage. In case the calculated humidex is less than the given temperature, it returns temperature itself.

      const humidex = getHumidex(30, 70); // returns 41
       

      This is using the formula from the Canadian Centre for Climate Services.

      -

      Parameters

      • temperature: number
      • humidity: number

      Returns number

    +

    Parameters

    • temperature: number
    • humidity: number

    Returns number

diff --git a/docs/functions/getId.html b/docs/functions/getId.html index 130b01b1..f1ccd216 100644 --- a/docs/functions/getId.html +++ b/docs/functions/getId.html @@ -1,2 +1,2 @@ -getId | Journalism - v1.15.3

Function getId

  • Creates a unique id with letters, numbers, but no spaces or special characters. By default, the length is 6 characters. Works in the browser and NodeJS (and other runtimes). Handy, but not cryptographically secure.

    -

    Parameters

    • length: number = 6

    Returns string

+getId | Journalism - v1.15.4

Function getId

  • Creates a unique id with letters, numbers, but no spaces or special characters. By default, the length is 6 characters. Works in the browser and NodeJS (and other runtimes). Handy, but not cryptographically secure.

    +

    Parameters

    • length: number = 6

    Returns string

diff --git a/docs/functions/getMahalanobisDistance.html b/docs/functions/getMahalanobisDistance.html index 854ef643..5f201ae7 100644 --- a/docs/functions/getMahalanobisDistance.html +++ b/docs/functions/getMahalanobisDistance.html @@ -1,2 +1,2 @@ -getMahalanobisDistance | Journalism - v1.15.3

Function getMahalanobisDistance

  • Computes the Mahalanobis distance. You first need to compute the inverted covariance matrix of your data with getCovarianceMatrix.

    -

    Parameters

    • x1: number[]
    • x2: number[]
    • invCovMatrix: number[][]

    Returns number

+getMahalanobisDistance | Journalism - v1.15.4

Function getMahalanobisDistance

  • Computes the Mahalanobis distance. You first need to compute the inverted covariance matrix of your data with getCovarianceMatrix.

    +

    Parameters

    • x1: number[]
    • x2: number[]
    • invCovMatrix: number[][]

    Returns number

diff --git a/docs/functions/getSeason.html b/docs/functions/getSeason.html index 75619c03..edb9212a 100644 --- a/docs/functions/getSeason.html +++ b/docs/functions/getSeason.html @@ -1,2 +1,2 @@ -getSeason | Journalism - v1.15.3

Function getSeason

  • Determines the current season based on a date (current date by default). Options include hemisphere (northern by default) and type (astronomical by default).

    -

    Parameters

    • options: {
          date?: Date;
          hemisphere?: "northern" | "southern";
          type?: "meteorological" | "astronomical";
      } = {}
      • Optionaldate?: Date
      • Optionalhemisphere?: "northern" | "southern"
      • Optionaltype?: "meteorological" | "astronomical"

    Returns
        | "winter"
        | "spring"
        | "summer"
        | "fall"

+getSeason | Journalism - v1.15.4

Function getSeason

  • Determines the current season based on a date (current date by default). Options include hemisphere (northern by default) and type (astronomical by default).

    +

    Parameters

    • options: {
          date?: Date;
          hemisphere?: "northern" | "southern";
          type?: "meteorological" | "astronomical";
      } = {}
      • Optionaldate?: Date
      • Optionalhemisphere?: "northern" | "southern"
      • Optionaltype?: "meteorological" | "astronomical"

    Returns
        | "winter"
        | "spring"
        | "summer"
        | "fall"

diff --git a/docs/functions/getSheetData.html b/docs/functions/getSheetData.html index 2998625b..24cf70e2 100644 --- a/docs/functions/getSheetData.html +++ b/docs/functions/getSheetData.html @@ -1,5 +1,5 @@ -getSheetData | Journalism - v1.15.3

Function getSheetData

  • Returns the data of a Google Sheet.

    -

    By default, this function looks for the API key in process.env.GOOGLE_PRIVATE_KEY and the service account email in process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL. If you don't have credentials, check this.

    +getSheetData | Journalism - v1.15.4

    Function getSheetData

    • Returns the data of a Google Sheet.

      +

      By default, this function looks for the API key in process.env.GOOGLE_PRIVATE_KEY and the service account email in process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL. If you don't have credentials, check this.

      // Fake url used as an example.
      const sheetUrl = "https://docs.google.com/spreadsheets/d/nrqo3oP4KMWYbELScQa8W1nHZPfIrA7LIz9UmcRE4GyJN/edit#gid=0";

      // Returning the data as an array of objects.
      const data = await getSheetData(data, sheetUrl);

      // Same but skipping first row.
      const data = await getSheetData(data, sheetUrl, { skip: 1});

      // You have an option to return the data as a CSV string. Useful if you just want to write the data somewhere.
      const csv = await getSheetData(data, sheetUrl, { csv: true });

      // If your API email and key are stored under different names in process.env, use the options.
      const csv = await getSheetData(data, sheetUrl, { apiEmail: "GG_EMAIL", apiKey: "GG_KEY" });
      @@ -9,4 +9,4 @@
    • OptionalapiKey?: string

      If your API key is stored under different names in process.env, use this option.

    • Optionalcsv?: boolean

      If true, the function will return a CSV string instead of an array of objects.

    • Optionalskip?: number

      The number of rows to skip before parsing the data. Defaults to 0.

      -

Returns Promise<string | DSVRowArray<string>>

+

Returns Promise<string | DSVRowArray<string>>

diff --git a/docs/functions/getStatCanTable.html b/docs/functions/getStatCanTable.html index 81242b94..98ab1ecc 100644 --- a/docs/functions/getStatCanTable.html +++ b/docs/functions/getStatCanTable.html @@ -1,4 +1,4 @@ -getStatCanTable | Journalism - v1.15.3

Function getStatCanTable

  • Returns the data from a Statistics Canada table as an array of objects. The first parameter is the pid value that can be found in the table url. The second parameter is an optional object specifying:

    +getStatCanTable | Journalism - v1.15.4

    Function getStatCanTable

    • Returns the data from a Statistics Canada table as an array of objects. The first parameter is the pid value that can be found in the table url. The second parameter is an optional object specifying:

      • the language
      • if the first character of the file should be skipped (sometimes the files are weirdly formatted)
      • @@ -7,4 +7,4 @@
        const data = await getStatCanTable('98100001')
         
        -

      Parameters

      • pid: string
      • options: {
            debug?: boolean;
            lang?: "en" | "fr";
            returnRawCSV?: boolean;
            skipFirstCharacter?: boolean;
        } = {}
        • Optionaldebug?: boolean
        • Optionallang?: "en" | "fr"
        • OptionalreturnRawCSV?: boolean
        • OptionalskipFirstCharacter?: boolean

      Returns Promise<string | DSVRowArray<string>>

    +

    Parameters

    • pid: string
    • options: {
          debug?: boolean;
          lang?: "en" | "fr";
          returnRawCSV?: boolean;
          skipFirstCharacter?: boolean;
      } = {}
      • Optionaldebug?: boolean
      • Optionallang?: "en" | "fr"
      • OptionalreturnRawCSV?: boolean
      • OptionalskipFirstCharacter?: boolean

    Returns Promise<string | DSVRowArray<string>>

diff --git a/docs/functions/invertMatrix.html b/docs/functions/invertMatrix.html index f21254e3..b0bcf235 100644 --- a/docs/functions/invertMatrix.html +++ b/docs/functions/invertMatrix.html @@ -1,2 +1,2 @@ -invertMatrix | Journalism - v1.15.3

Function invertMatrix

  • Computes the invert of a square matrix.

    -

    Parameters

    • matrix: number[][]

    Returns number[][]

+invertMatrix | Journalism - v1.15.4

Function invertMatrix

  • Computes the invert of a square matrix.

    +

    Parameters

    • matrix: number[][]

    Returns number[][]

diff --git a/docs/functions/mortgageInsurancePremium.html b/docs/functions/mortgageInsurancePremium.html index 158861fe..1678fa9f 100644 --- a/docs/functions/mortgageInsurancePremium.html +++ b/docs/functions/mortgageInsurancePremium.html @@ -1,7 +1,7 @@ -mortgageInsurancePremium | Journalism - v1.15.3

Function mortgageInsurancePremium

  • Calculates the mortgage insurance premium based on the property value and down payment. The returned value is rounded to the nearest integer. Based on the Financial Consumer Agency of Canada calculator.

    +mortgageInsurancePremium | Journalism - v1.15.4

    Function mortgageInsurancePremium

    • Calculates the mortgage insurance premium based on the property value and down payment. The returned value is rounded to the nearest integer. Based on the Financial Consumer Agency of Canada calculator.

      // Returns 19_000
      const insurancePremium = mortgageInsurancePremium(500_000, 25_000)

      Parameters

      • purchasePrice: number

        The price of the purchased property.

      • downPayment: number

        The amount of money paid upfront.

        -

      Returns number

    +

Returns number

diff --git a/docs/functions/mortgageMaxAmount.html b/docs/functions/mortgageMaxAmount.html index 3dffc0a8..be197759 100644 --- a/docs/functions/mortgageMaxAmount.html +++ b/docs/functions/mortgageMaxAmount.html @@ -1,4 +1,4 @@ -mortgageMaxAmount | Journalism - v1.15.3

Function mortgageMaxAmount

  • Calculates the maximum purchase price (and other variables) for a property a person can afford and the related mortgage it would qualify for based on annual income, down payment, mortgage interest rate, and additional options.

    +mortgageMaxAmount | Journalism - v1.15.4

    Function mortgageMaxAmount

    • Calculates the maximum purchase price (and other variables) for a property a person can afford and the related mortgage it would qualify for based on annual income, down payment, mortgage interest rate, and additional options.

      // With an annual income of $100,000, a down payment of $25,000, and a rate of 5.25%.
      const results = maxMortgageAmount(100_000, 25_000, 5.25)
      // results = {
      // annualIncome: 100000,
      // downPayment: 25000,
      // rate: 5.25,
      // rateTested: 7.25,
      // purchasePrice: 307000,
      // mortgageAmount: 293280,
      // insurancePremium: 11280,
      // monthlyMortgagePayment: 2099.65,
      // grossDebtServiceRatio: 0.32,
      // totalDebtServiceRatio: 0.32,
      // reason: "debt limit",
      // monthlyDebtPayment: 0,
      // monthlyHeating: 175,
      // isHeatingEstimate: true,
      // monthlyTax: 385,
      // isTaxEstimate: true,
      // monthlyCondoFees: 0,
      // }
      @@ -10,4 +10,4 @@
    • OptionalmonthlyDebtPayment?: number

      The monthly debt payment of the borrower. Defaults to 0.

    • OptionalmonthlyHeating?: number

      The monthly heating cost. Defaults to $175.

    • OptionalmonthlyTax?: number

      The monthly property tax. Default to 1.5% of the purchase price.

      -

Returns {
    annualIncome: number;
    downPayment: number;
    grossDebtServiceRatio: number;
    insurancePremium: number;
    isHeatingEstimate: boolean;
    isTaxEstimate: boolean;
    monthlyCondoFees: number;
    monthlyDebtPayment: number;
    monthlyHeating: number;
    monthlyMortgagePayment: number;
    monthlyTax: number;
    mortgageAmount: number;
    purchasePrice: number;
    rate: number;
    rateTested: number;
    reason: string;
    totalDebtServiceRatio: number;
}

  • annualIncome: number
  • downPayment: number
  • grossDebtServiceRatio: number
  • insurancePremium: number
  • isHeatingEstimate: boolean
  • isTaxEstimate: boolean
  • monthlyCondoFees: number
  • monthlyDebtPayment: number
  • monthlyHeating: number
  • monthlyMortgagePayment: number
  • monthlyTax: number
  • mortgageAmount: number
  • purchasePrice: number
  • rate: number
  • rateTested: number
  • reason: string
  • totalDebtServiceRatio: number
+

Returns {
    annualIncome: number;
    downPayment: number;
    grossDebtServiceRatio: number;
    insurancePremium: number;
    isHeatingEstimate: boolean;
    isTaxEstimate: boolean;
    monthlyCondoFees: number;
    monthlyDebtPayment: number;
    monthlyHeating: number;
    monthlyMortgagePayment: number;
    monthlyTax: number;
    mortgageAmount: number;
    purchasePrice: number;
    rate: number;
    rateTested: number;
    reason: string;
    totalDebtServiceRatio: number;
}

  • annualIncome: number
  • downPayment: number
  • grossDebtServiceRatio: number
  • insurancePremium: number
  • isHeatingEstimate: boolean
  • isTaxEstimate: boolean
  • monthlyCondoFees: number
  • monthlyDebtPayment: number
  • monthlyHeating: number
  • monthlyMortgagePayment: number
  • monthlyTax: number
  • mortgageAmount: number
  • purchasePrice: number
  • rate: number
  • rateTested: number
  • reason: string
  • totalDebtServiceRatio: number
diff --git a/docs/functions/mortgagePayments.html b/docs/functions/mortgagePayments.html index b9313178..ac818019 100644 --- a/docs/functions/mortgagePayments.html +++ b/docs/functions/mortgagePayments.html @@ -1,4 +1,4 @@ -mortgagePayments | Journalism - v1.15.3

Function mortgagePayments

  • Returns fixed rate mortgage payments in an array. Each payment is an object with the paymentId, the payment amount, the interest and capital portions of the payment, the remaining mortgage balance, and the total amount paid, total interest paid, and total capital reimbursed so far. The calculations have been tested for Canada, which requires fixed rate mortgages to be compounded semi-annually by law. But you can change the annualCompounding in the options.

    +mortgagePayments | Journalism - v1.15.4

    Function mortgagePayments

    • Returns fixed rate mortgage payments in an array. Each payment is an object with the paymentId, the payment amount, the interest and capital portions of the payment, the remaining mortgage balance, and the total amount paid, total interest paid, and total capital reimbursed so far. The calculations have been tested for Canada, which requires fixed rate mortgages to be compounded semi-annually by law. But you can change the annualCompounding in the options.

      If the amortizationPeriod is smaller than the term, an error is thrown.

      These options can be passed in an object as the last parameter:

        @@ -7,5 +7,5 @@
      • annualCompounding: how many times the mortgage should be compounded per year. By default, it's 2.
      • debug: Will log extra information if true.
      -

      Calculations are based on https://www.yorku.ca/amarshal/mortgage.htm and https://www.mikesukmanowsky.com/blog/a-guide-to-canadian-mortgage-calculations

      -

      Parameters

      • mortageAmount: number
      • rate: number
      • paymentFrequency:
            | "weekly"
            | "biWeekly"
            | "monthly"
            | "semiMonthly"
            | "acceleratedWeekly"
            | "acceleratedBiWeekly"
      • term: number
      • amortizationPeriod: number
      • options: {
            annualCompounding?: number;
            debug?: boolean;
            decimals?: number;
            id?: string;
        } = {}
        • OptionalannualCompounding?: number
        • Optionaldebug?: boolean
        • Optionaldecimals?: number
        • Optionalid?: string

      Returns {
          amountPaid: number;
          balance: number;
          capital: number;
          capitalPaid: number;
          id?: string;
          interest: number;
          interestPaid: number;
          payment: number;
          paymentId: number;
      }[]

    +

    Calculations are based on https://www.yorku.ca/amarshal/mortgage.htm and https://www.mikesukmanowsky.com/blog/a-guide-to-canadian-mortgage-calculations

    +

    Parameters

    • mortageAmount: number
    • rate: number
    • paymentFrequency:
          | "weekly"
          | "biWeekly"
          | "monthly"
          | "semiMonthly"
          | "acceleratedWeekly"
          | "acceleratedBiWeekly"
    • term: number
    • amortizationPeriod: number
    • options: {
          annualCompounding?: number;
          debug?: boolean;
          decimals?: number;
          id?: string;
      } = {}
      • OptionalannualCompounding?: number
      • Optionaldebug?: boolean
      • Optionaldecimals?: number
      • Optionalid?: string

    Returns {
        amountPaid: number;
        balance: number;
        capital: number;
        capitalPaid: number;
        id?: string;
        interest: number;
        interestPaid: number;
        payment: number;
        paymentId: number;
    }[]

diff --git a/docs/functions/overwriteSheetData.html b/docs/functions/overwriteSheetData.html index 023a883f..ba60b1c3 100644 --- a/docs/functions/overwriteSheetData.html +++ b/docs/functions/overwriteSheetData.html @@ -1,5 +1,5 @@ -overwriteSheetData | Journalism - v1.15.3

Function overwriteSheetData

  • Clears a Google Sheet and populates it with new data.

    -

    By default, this function looks for the API key in process.env.GOOGLE_PRIVATE_KEY and the service account email in process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL. If you don't have credentials, check this.

    +overwriteSheetData | Journalism - v1.15.4

    Function overwriteSheetData

    • Clears a Google Sheet and populates it with new data.

      +

      By default, this function looks for the API key in process.env.GOOGLE_PRIVATE_KEY and the service account email in process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL. If you don't have credentials, check this.

      // The data needs to be an array of objects. The keys of the first object will be used to create the header row.
      const data = [
      { first: "Nael", last: "Shiab" },
      { first: "Andrew", last: "Ryan" },
      ];
      // Fake url used as an example.
      const sheetUrl = "https://docs.google.com/spreadsheets/d/nrqo3oP4KMWYbELScQa8W1nHZPfIrA7LIz9UmcRE4GyJN/edit#gid=0";

      // Clearing the sheet and then populating it.
      await overwriteSheetData(data, sheetUrl);

      // Same thing but with raw values. Google Sheet won't try to guess the data types and won't format or parse the values.
      await overwriteSheetData(data, sheetUrl, { raw: true });

      // Adding the UTC date of the update before the data.
      await overwriteSheetData(data, sheetUrl, { lastUpdate: true });

      // You can also format the date to a specific time zone.
      await overwriteSheetData(data, sheetUrl, { lastUpdate: true, timeZone: "Canada/Eastern" });

      // The prepend option allows you to add extra text on the first row.
      await overwriteSheetData(data, sheetUrl, { prepend: "Contact xxxx.xxxx@gmail.com for more information", lastUpdate: true, timeZone: "Canada/Eastern" });

      // If your API email and key are stored under different names in process.env, use the options.
      await overwriteSheetData(data, sheetUrl, { apiEmail: "GG_EMAIL", apiKey: "GG_KEY" });
      @@ -12,4 +12,4 @@
    • Optionalprepend?: string

      Text to be added before the data.

    • Optionalraw?: boolean

      If true, Google Sheet won't try to guess the data type and won't format or parse the values.

    • OptionaltimeZone?:
          | "Canada/Atlantic"
          | "Canada/Central"
          | "Canada/Eastern"
          | "Canada/Mountain"
          | "Canada/Newfoundland"
          | "Canada/Pacific"
          | "Canada/Saskatchewan"
          | "Canada/Yukon"

      If lastUpdate is true, you can use this option to format the date to a specific time zone.

      -

Returns Promise<void>

+

Returns Promise<void>

diff --git a/docs/functions/prettyDuration.html b/docs/functions/prettyDuration.html index 33a98694..ad2c128c 100644 --- a/docs/functions/prettyDuration.html +++ b/docs/functions/prettyDuration.html @@ -1,5 +1,5 @@ -prettyDuration | Journalism - v1.15.3

Function prettyDuration

  • Returns the duration as a string in terms of milliseconds, seconds, minutes, hours, and days.

    +prettyDuration | Journalism - v1.15.4

    Function prettyDuration

    • Returns the duration as a string in terms of milliseconds, seconds, minutes, hours, and days.

      // A starting Date somewhere in your code
      const startDate = new Date() // or Date.now()

      // When you want to know the elapsed duration, pass the start date
      const duration = prettyDuration(startDate)
      // Returns something like "22 days, 6 h, 3 min, 15 sec, 3 ms"

      // If you want to console.log it, set the option log to true
      prettyDuration(startDate, {log: true})

      // You can also use a prefix and/or suffix
      prettyDuration(startDate, {log: true, prefix: "Total duration: ", suffix: " (Main function)"})
      // Returns and logs something like "Total duration: 3 min, 15 sec, 3 ms (Main function)"

      // If you want to format the duration between two specific dates, use the end option.
      prettyDuration(new Date("2024-01-01T17:00:00"), { end: new Date("2024-01-23T23:03:15") })
      // Returns "22 days, 6 h, 3 min, 15 sec, 0 ms"
      -

      Parameters

      • start: number | Date
      • options: {
            end?: number | Date;
            log?: boolean;
            prefix?: string;
            suffix?: string;
        } = {}
        • Optionalend?: number | Date
        • Optionallog?: boolean
        • Optionalprefix?: string
        • Optionalsuffix?: string

      Returns string

    +

    Parameters

    • start: number | Date
    • options: {
          end?: number | Date;
          log?: boolean;
          prefix?: string;
          suffix?: string;
      } = {}
      • Optionalend?: number | Date
      • Optionallog?: boolean
      • Optionalprefix?: string
      • Optionalsuffix?: string

    Returns string

diff --git a/docs/functions/publishChartDW.html b/docs/functions/publishChartDW.html index edf19d20..47c5c4ca 100644 --- a/docs/functions/publishChartDW.html +++ b/docs/functions/publishChartDW.html @@ -1,5 +1,5 @@ -publishChartDW | Journalism - v1.15.3

Function publishChartDW

  • Publishes the specified Datawrapper chart, table, or map. By default, this function looks for the API key in process.env.DATAWRAPPER_KEY.

    +publishChartDW | Journalism - v1.15.4

    Function publishChartDW

    • Publishes the specified Datawrapper chart, table, or map. By default, this function looks for the API key in process.env.DATAWRAPPER_KEY.

      const chartID = "myChartId"
      await publishChartDW(chartID)

      // If your API key is stored under a different name in process.env, use the options.
      await publishChartDW(chartID, { apiKey: "DW_KEY" })
      -

      Parameters

      • chartId: string
      • options: {
            apiKey?: string;
            returnResponse?: boolean;
        } = {}
        • OptionalapiKey?: string
        • OptionalreturnResponse?: boolean

      Returns Promise<void | Response>

    +

    Parameters

    • chartId: string
    • options: {
          apiKey?: string;
          returnResponse?: boolean;
      } = {}
      • OptionalapiKey?: string
      • OptionalreturnResponse?: boolean

    Returns Promise<void | Response>

diff --git a/docs/functions/round.html b/docs/functions/round.html index d5b7f934..775c1666 100644 --- a/docs/functions/round.html +++ b/docs/functions/round.html @@ -1,4 +1,4 @@ -round | Journalism - v1.15.3

Function round

  • Round a number. By default, round to the nearest integer.

    +round | Journalism - v1.15.4

    Function round

    • Round a number. By default, round to the nearest integer.

      const string = round(1234.567, { decimals: 1 })
      // returns 1,235.6
      @@ -9,4 +9,4 @@
    • significantDigits: The number of digits to keep. Significant digits start being counted at the first non-zero digit. For example, 0.004622 with 1 significant digit will the rounded to 0.005.
    • try: by default, the function throws an error if the passed value is not a number. With try set to true, no error is thrown but the returned value is NaN.
    -

    Parameters

    • number: number
    • options: {
          decimals?: number;
          nearestInteger?: number;
          significantDigits?: number;
          try?: boolean;
      } = {}
      • Optionaldecimals?: number
      • OptionalnearestInteger?: number
      • OptionalsignificantDigits?: number
      • Optionaltry?: boolean

    Returns number

+

Parameters

  • number: number
  • options: {
        decimals?: number;
        nearestInteger?: number;
        significantDigits?: number;
        try?: boolean;
    } = {}
    • Optionaldecimals?: number
    • OptionalnearestInteger?: number
    • OptionalsignificantDigits?: number
    • Optionaltry?: boolean

Returns number

diff --git a/docs/functions/savePlotChart.html b/docs/functions/savePlotChart.html index 585af1df..d32db308 100644 --- a/docs/functions/savePlotChart.html +++ b/docs/functions/savePlotChart.html @@ -1,5 +1,5 @@ -savePlotChart | Journalism - v1.15.3

Function savePlotChart

  • Saves an Observable Plot chart as an image. You must use the Plot.dot syntax and install puppeteer (npm i puppeteer).

    +savePlotChart | Journalism - v1.15.4

    Function savePlotChart

    • Saves an Observable Plot chart as an image. You must use the Plot.dot syntax and install puppeteer (npm i puppeteer).

      import * as Plot from "@observablehq/plot"

      // The data must be an array of objects.
      const data = [{ salary: 75000, hireDate: new Date("2023-12-22") }, ...]

      // The Plot options must be wrapped into a function and use the Plot. syntax.
      const chart = () => Plot.plot({
      marks: [
      Plot.dot(data, {x: "hireDate", y: "salary"})
      ]
      })

      // Change the extension to .jpeg to get a JPEG file.
      const path = "./my-chart.png"

      await savePlotChart(data, chart, path)
      -

      Parameters

      • data: {
            [key: string]: unknown;
        }[]
      • makeChart: ((data: {
            [key: string]: unknown;
        }[]) => SVGSVGElement | HTMLElement)
          • (data): SVGSVGElement | HTMLElement
          • Parameters

            • data: {
                  [key: string]: unknown;
              }[]

            Returns SVGSVGElement | HTMLElement

      • path: string

      Returns Promise<void>

    +

    Parameters

    • data: {
          [key: string]: unknown;
      }[]
    • makeChart: ((data: {
          [key: string]: unknown;
      }[]) => SVGSVGElement | HTMLElement)
        • (data): SVGSVGElement | HTMLElement
        • Parameters

          • data: {
                [key: string]: unknown;
            }[]

          Returns SVGSVGElement | HTMLElement

    • path: string

    Returns Promise<void>

diff --git a/docs/functions/styledLayerDescriptor.html b/docs/functions/styledLayerDescriptor.html index 5d3d6593..9fc6bee5 100644 --- a/docs/functions/styledLayerDescriptor.html +++ b/docs/functions/styledLayerDescriptor.html @@ -1,5 +1,5 @@ -styledLayerDescriptor | Journalism - v1.15.3

Function styledLayerDescriptor

  • Returns the OpenGIS Styled Layer Descriptor encoded for an URL. The required parameters are the layer and the color scale.

    +styledLayerDescriptor | Journalism - v1.15.4

    Function styledLayerDescriptor

    • Returns the OpenGIS Styled Layer Descriptor encoded for an URL. The required parameters are the layer and the color scale.

      // Returns the SLD for the GDPS.ETA_TT layer with a color scale going from blue to red.
      const sdl = styledLayerDescriptor("GDPS.ETA_TT", [
      { color: "#550c24", value: 100 },
      { color: "#7f2e34", value: 30 },
      { color: "#c26847", value: 20 },
      { color: "#bdbb7a", value: 10 },
      { color: "#e0e9f0", value: 0 },
      { color: "#97b4cd", value: -10 },
      { color: "#5881a1", value: -20 },
      { color: "#334f60", value: -30 },
      { color: "#21353f", value: -100 },
      ])

      // The sdl can now be used in a WMS request as SLD_BODY
      const url = `https://geo.weather.gc.ca/geomet?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&BBOX=-90,-180,90,180&CRS=EPSG:4326&WIDTH=2400&HEIGHT=1200&LAYERS=GDPS.ETA_TT&FORMAT=image/jpeg&SLD_BODY=${sld}`
      -

      Parameters

      • layer: string
      • colorScale: {
            color: string;
            value: number;
        }[]

      Returns string

    +

    Parameters

    • layer: string
    • colorScale: {
          color: string;
          value: number;
      }[]

    Returns string

diff --git a/docs/functions/unzip.html b/docs/functions/unzip.html index c6a2cec0..b903e85b 100644 --- a/docs/functions/unzip.html +++ b/docs/functions/unzip.html @@ -1,4 +1,4 @@ -unzip | Journalism - v1.15.3

Function unzip

  • Unzips a file and outputs the result in a folder.

    +unzip | Journalism - v1.15.4

    Function unzip

    • Unzips a file and outputs the result in a folder.

      unzip("files.zip", "./output/")
       
      @@ -6,4 +6,4 @@
      unzip("files.zip", "./output/", { deleteZippedFile: true })
       
      -

      Parameters

      • zippedFile: string
      • output: string
      • options: {
            deleteZippedFile?: boolean;
        } = {}
        • OptionaldeleteZippedFile?: boolean

      Returns void

    +

    Parameters

    • zippedFile: string
    • output: string
    • options: {
          deleteZippedFile?: boolean;
      } = {}
      • OptionaldeleteZippedFile?: boolean

    Returns void

diff --git a/docs/functions/updateAnnotationsDW.html b/docs/functions/updateAnnotationsDW.html index 0361a985..35cbd0a3 100644 --- a/docs/functions/updateAnnotationsDW.html +++ b/docs/functions/updateAnnotationsDW.html @@ -1,5 +1,5 @@ -updateAnnotationsDW | Journalism - v1.15.3

Function updateAnnotationsDW

  • Updates annotations in on a chart. By default, this function looks for the API key in process.env.DATAWRAPPER_KEY.

    +updateAnnotationsDW | Journalism - v1.15.4

    Function updateAnnotationsDW

    • Updates annotations in on a chart. By default, this function looks for the API key in process.env.DATAWRAPPER_KEY.

      import { updateAnnotationsDW } from "journalism"

      const chartID = "myChartId"
      const myAnnotations = [
      {
      "x": "2024/08/30 01:52",
      "y": "14496235",
      "text": "This is an annotation!",
      },
      {
      "x": "2024/06/29",
      "y": "15035128",
      "dy": 50,
      "text": "This is also some text, but with an arrow!",
      "connectorLine": {
      "enabled": true,
      "type": "straight",
      "arrowHead": "lines"
      },
      "mobileFallback": false
      }
      ]

      await updateAnnotationsDW(chartID, myAnnotations)

      // If your API key is stored under a different name in process.env, use the options.
      await updateAnnotationsDW(chartID, myAnnotations, { apiKey: "DW_KEY" })
      -

      Parameters

      • chartId: string
      • annotations: {
            align?:
                | "tr"
                | "tl"
                | "tc"
                | "ml"
                | "mc"
                | "mr"
                | "bl"
                | "bc"
                | "br";
            bg?: boolean;
            bold?: boolean;
            color?: string;
            connectorLine?: {
                arrowHead?: false | "lines" | "triangle";
                circle?: boolean;
                circleRadius?: number;
                circleStyle?: string;
                enabled?: boolean;
                inheritColor?: boolean;
                stroke?: 1 | 3 | 2;
                targetPadding?: number;
                type?: "straight" | "curveRight" | "curveLeft";
            };
            dx?: number;
            dy?: number;
            italic?: boolean;
            mobileFallback?: boolean;
            showDesktop?: boolean;
            showMobile?: boolean;
            size?: number;
            text: string;
            underline?: boolean;
            width?: number;
            x: string;
            y: string;
        }[]
      • options: {
            apiKey?: string;
            returnResponse?: boolean;
        } = {}
        • OptionalapiKey?: string
        • OptionalreturnResponse?: boolean

      Returns Promise<void | Response>

    +

    Parameters

    • chartId: string
    • annotations: {
          align?:
              | "tr"
              | "tl"
              | "tc"
              | "ml"
              | "mc"
              | "mr"
              | "bl"
              | "bc"
              | "br";
          bg?: boolean;
          bold?: boolean;
          color?: string;
          connectorLine?: {
              arrowHead?: false | "lines" | "triangle";
              circle?: boolean;
              circleRadius?: number;
              circleStyle?: string;
              enabled?: boolean;
              inheritColor?: boolean;
              stroke?: 1 | 3 | 2;
              targetPadding?: number;
              type?: "straight" | "curveRight" | "curveLeft";
          };
          dx?: number;
          dy?: number;
          italic?: boolean;
          mobileFallback?: boolean;
          showDesktop?: boolean;
          showMobile?: boolean;
          size?: number;
          text: string;
          underline?: boolean;
          width?: number;
          x: string;
          y: string;
      }[]
    • options: {
          apiKey?: string;
          returnResponse?: boolean;
      } = {}
      • OptionalapiKey?: string
      • OptionalreturnResponse?: boolean

    Returns Promise<void | Response>

diff --git a/docs/functions/updateDataDW.html b/docs/functions/updateDataDW.html index ad15759b..45fca568 100644 --- a/docs/functions/updateDataDW.html +++ b/docs/functions/updateDataDW.html @@ -1,4 +1,4 @@ -updateDataDW | Journalism - v1.15.3

Function updateDataDW

  • Updates the data of a specified Datawrapper chart, table or map. By default, this function looks for the API key in process.env.DATAWRAPPER_KEY.

    +updateDataDW | Journalism - v1.15.4

    Function updateDataDW

    • Updates the data of a specified Datawrapper chart, table or map. By default, this function looks for the API key in process.env.DATAWRAPPER_KEY.

      Example for a chart.

      import { updateDataDW, dataAsCsv } from "journalism"

      const chartID = "myChartId"

      const data = [
      { salary: 75000, hireDate: new Date("2022-12-15") },
      ...
      ]
      const dataForChart = dataAsCsv(data)

      await updateDataDW(chartID, dataForChart)

      // If your API key is stored under a different name in process.env, use the options.
      await updateDataDW(chartID, dataForChart, { apiKey: "DW_KEY" })
      @@ -7,4 +7,4 @@
      import { updateDataDW } from "journalism"

      const mapID = "myMapId"

      const geojson = {
      "type": "FeatureCollection",
      "features": [
      {
      "type": "Feature",
      "properties": {},
      "geometry": {
      "coordinates": [
      [
      [
      11.127454320325711,
      20.34856592751224
      ],
      [
      11.127454320325711,
      -13.781306861158996
      ],
      [
      55.68071875381875,
      -13.781306861158996
      ],
      [
      55.68071875381875,
      20.34856592751224
      ],
      [
      11.127454320325711,
      20.34856592751224
      ]
      ]
      ],
      "type": "Polygon"
      }
      }
      ]
      }

      const dataForMap = {
      "markers": [
      {
      "id": "m1",
      "type": "area",
      "visible": true,
      "exactShape": true,
      "fill": true,
      "stroke": true,
      "properties": {
      "fill": "#15607a",
      "fill-opacity": 0.2,
      "stroke": "#15607a",
      "stroke-width": 1,
      "stroke-opacity": 1,
      "stroke-dasharray": "100000",
      "pattern": "solid",
      "pattern-line-width": 2,
      "pattern-line-gap": 2
      },
      "feature": geojson
      }
      ]
      }

      await updateDataDW(mapID, JSON.stringify(dataForMap))

      // If your API key is stored under a different name in process.env, use the options.
      await updateDataDW(mapID, JSON.stringify(dataForMap), { apiKey: "DW_KEY" })
      -

      Parameters

      • chartId: string
      • data: string
      • options: {
            apiKey?: string;
            returnResponse?: boolean;
        } = {}
        • OptionalapiKey?: string
        • OptionalreturnResponse?: boolean

      Returns Promise<void | Response>

    +

    Parameters

    • chartId: string
    • data: string
    • options: {
          apiKey?: string;
          returnResponse?: boolean;
      } = {}
      • OptionalapiKey?: string
      • OptionalreturnResponse?: boolean

    Returns Promise<void | Response>

diff --git a/docs/functions/updateNotesDW.html b/docs/functions/updateNotesDW.html index 63de35cf..22fa3556 100644 --- a/docs/functions/updateNotesDW.html +++ b/docs/functions/updateNotesDW.html @@ -1,5 +1,5 @@ -updateNotesDW | Journalism - v1.15.3

Function updateNotesDW

  • Updates notes field for a specified Datawrapper chart, table or map. By default, this function looks for the API key in process.env.DATAWRAPPER_KEY.

    +updateNotesDW | Journalism - v1.15.4

    Function updateNotesDW

    • Updates notes field for a specified Datawrapper chart, table or map. By default, this function looks for the API key in process.env.DATAWRAPPER_KEY.

      import { updateNotesDW, formatDate } from "journalism"

      const chartID = "myChartId"
      const dateString = formatDate(new Date(), "Month DD, YYYY, at HH:MM period", { abbreviations: true })
      const note = `This chart was last updated on ${dateString}`

      await updateNotesDW(chartID, note)

      // If your API key is stored under a different name in process.env, use the options.
      await updateNotesDW(chartID, note, { apiKey: "DW_KEY" })
      -

      Parameters

      • chartId: string
      • note: string
      • options: {
            apiKey?: string;
            returnResponse?: boolean;
        } = {}
        • OptionalapiKey?: string
        • OptionalreturnResponse?: boolean

      Returns Promise<void | Response>

    +

    Parameters

    • chartId: string
    • note: string
    • options: {
          apiKey?: string;
          returnResponse?: boolean;
      } = {}
      • OptionalapiKey?: string
      • OptionalreturnResponse?: boolean

    Returns Promise<void | Response>

diff --git a/docs/functions/zip.html b/docs/functions/zip.html index 832d27d6..3766308e 100644 --- a/docs/functions/zip.html +++ b/docs/functions/zip.html @@ -1,5 +1,5 @@ -zip | Journalism - v1.15.3

Function zip

  • Zips multiple files together. To zip an entire folder, pass the folder path as the first parameter. To zip specific files, pass their path as an array of strings. The function will create the path of the zipped file if it doesn't exist.

    +zip | Journalism - v1.15.4

    Function zip

    • Zips multiple files together. To zip an entire folder, pass the folder path as the first parameter. To zip specific files, pass their path as an array of strings. The function will create the path of the zipped file if it doesn't exist.

      // Entire folder
      zip("./data", "./data.zip")

      // Specific files
      zip(["./file1.json", "./file2.txt", "./file3.jpg"], "./files.zip")
      -

      Parameters

      • files: string | string[]
      • zipFile: string

      Returns void

    +

    Parameters

    • files: string | string[]
    • zipFile: string

    Returns void

diff --git a/docs/index.html b/docs/index.html index c2dfa36c..a5272c53 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,4 +1,4 @@ -Journalism - v1.15.3

Journalism - v1.15.3

Index

Dataviz

publishChartDW +Journalism - v1.15.4

Journalism - v1.15.4

Index

Dataviz

Web scraping

+