fix: Formatting + avg => geomMean

This commit is contained in:
NunoSempere 2022-01-29 16:06:16 -05:00
parent e610d798d3
commit 5ec31fa365
3 changed files with 515 additions and 429 deletions

View File

@ -1,71 +1,85 @@
/* Imports*/ /* Imports*/
import React from 'react'; import React from "react";
import { numToAlphabeticalString, formatLargeOrSmall, avg } from "../lib/utils.js" import {
numToAlphabeticalString,
formatLargeOrSmall,
avg,
geomMean,
} from "../lib/utils.js";
/* Functions */ /* Functions */
const pathPlusLink = (pathSoFar, link) => { const pathPlusLink = (pathSoFar, link) => {
return [...pathSoFar, link] return [...pathSoFar, link];
// previously: pathSoFar.concat(link).flat() // previously: pathSoFar.concat(link).flat()
// Note that concat is not destructive // Note that concat is not destructive
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
} };
async function findPathsWithoutPrunning({ async function findPathsWithoutPrunning({
sourceElementId, targetElementId, sourceElementId,
maxLengthOfPath, pathSoFar, targetElementId,
links, nodes maxLengthOfPath,
pathSoFar,
links,
nodes,
}) { }) {
// This is an un-used function which might make findPaths more understandable // This is an un-used function which might make findPaths more understandable
// It uses the same recursive functionality // It uses the same recursive functionality
// but has no path prunning // but has no path prunning
let paths = [] let paths = [];
/* Path traversing */ /* Path traversing */
if (maxLengthOfPath > 0) { if (maxLengthOfPath > 0) {
for (let link of links) { // vs let link of linksNow in findPaths for (let link of links) {
// vs let link of linksNow in findPaths
if ( if (
((link.source == sourceElementId) && (link.target == targetElementId)) || (link.source == sourceElementId && link.target == targetElementId) ||
((link.source == targetElementId) && (link.target == sourceElementId)) (link.source == targetElementId && link.target == sourceElementId)
) { // direct Path ) {
let newPath = pathPlusLink(pathSoFar, link) // direct Path
paths.push(newPath) let newPath = pathPlusLink(pathSoFar, link);
} else if ((link.source == sourceElementId)) { paths.push(newPath);
} else if (link.source == sourceElementId) {
let newPaths = await findPaths({ let newPaths = await findPaths({
pathSoFar: pathPlusLink(pathSoFar, link), pathSoFar: pathPlusLink(pathSoFar, link),
maxLengthOfPath: (maxLengthOfPath - 1), maxLengthOfPath: maxLengthOfPath - 1,
sourceElementId: link.target, sourceElementId: link.target,
targetElementId, targetElementId,
links: links, // vs let link of linksInner in findPaths links: links, // vs let link of linksInner in findPaths
nodes nodes,
}) });
if (newPaths.length != 0) { if (newPaths.length != 0) {
paths.push(...newPaths) paths.push(...newPaths);
} }
} else if ((link.target == sourceElementId)) { } else if (link.target == sourceElementId) {
let newPaths = await findPaths({ let newPaths = await findPaths({
pathSoFar: pathPlusLink(pathSoFar, link), pathSoFar: pathPlusLink(pathSoFar, link),
maxLengthOfPath: (maxLengthOfPath - 1), maxLengthOfPath: maxLengthOfPath - 1,
sourceElementId: link.source, sourceElementId: link.source,
targetElementId, targetElementId,
links: links, // vs let link of linksInner in findPaths links: links, // vs let link of linksInner in findPaths
nodes nodes,
}) });
if (newPaths.length != 0) { if (newPaths.length != 0) {
paths.push(...newPaths) paths.push(...newPaths);
} }
} }
} }
} }
return paths return paths;
} }
async function findPaths({ async function findPaths({
sourceElementId, sourceElementPosition, sourceElementId,
targetElementId, targetElementPosition, sourceElementPosition,
maxLengthOfPath, pathSoFar, targetElementId,
links, nodes targetElementPosition,
maxLengthOfPath,
pathSoFar,
links,
nodes,
}) { }) {
// This is the key path finding function // This is the key path finding function
// It finds the path from one element to another, recursively // It finds the path from one element to another, recursively
@ -74,117 +88,133 @@ async function findPaths({
// traverse only those which are between the origin and target links // traverse only those which are between the origin and target links
// this requires us to have a notion of "between" // this requires us to have a notion of "between"
let paths = [] let paths = [];
/* Path prunning*/ /* Path prunning*/
let minPos = Math.min(sourceElementPosition, targetElementPosition) let minPos = Math.min(sourceElementPosition, targetElementPosition);
let maxPos = Math.max(sourceElementPosition, targetElementPosition) let maxPos = Math.max(sourceElementPosition, targetElementPosition);
let linksInner = links.filter(link => let linksInner = links.filter(
(minPos <= link.sourceElementPosition && link.sourceElementPosition <= maxPos) && (link) =>
(minPos <= link.targetElementPosition && link.targetElementPosition <= maxPos) minPos <= link.sourceElementPosition &&
) link.sourceElementPosition <= maxPos &&
let linksNow = linksInner.filter(link => (link.source == sourceElementId || link.target == sourceElementId)) minPos <= link.targetElementPosition &&
link.targetElementPosition <= maxPos
);
let linksNow = linksInner.filter(
(link) => link.source == sourceElementId || link.target == sourceElementId
);
/* Path traversing */ /* Path traversing */
if (maxLengthOfPath > 0) { if (maxLengthOfPath > 0) {
for (let link of linksNow) { for (let link of linksNow) {
if ( if (
((link.source == sourceElementId) && (link.target == targetElementId)) || (link.source == sourceElementId && link.target == targetElementId) ||
((link.source == targetElementId) && (link.target == sourceElementId)) (link.source == targetElementId && link.target == sourceElementId)
) { // direct Path ) {
let newPath = pathPlusLink(pathSoFar, link) // direct Path
paths.push(newPath) let newPath = pathPlusLink(pathSoFar, link);
} else if ((link.source == sourceElementId)) { paths.push(newPath);
} else if (link.source == sourceElementId) {
let newPaths = await findPaths({ let newPaths = await findPaths({
pathSoFar: pathPlusLink(pathSoFar, link), pathSoFar: pathPlusLink(pathSoFar, link),
maxLengthOfPath: (maxLengthOfPath - 1), maxLengthOfPath: maxLengthOfPath - 1,
sourceElementPosition: link.sourceElementPosition, sourceElementPosition: link.sourceElementPosition,
sourceElementId: link.target, sourceElementId: link.target,
targetElementId, targetElementPosition, targetElementId,
targetElementPosition,
links: linksInner, links: linksInner,
nodes nodes,
}) });
if (newPaths.length != 0) { if (newPaths.length != 0) {
paths.push(...newPaths) paths.push(...newPaths);
} }
} else if ((link.target == sourceElementId)) { } else if (link.target == sourceElementId) {
let newPaths = await findPaths({ let newPaths = await findPaths({
pathSoFar: pathPlusLink(pathSoFar, link), pathSoFar: pathPlusLink(pathSoFar, link),
maxLengthOfPath: (maxLengthOfPath - 1), maxLengthOfPath: maxLengthOfPath - 1,
sourceElementPosition: link.sourceElementPosition, sourceElementPosition: link.sourceElementPosition,
sourceElementId: link.source, sourceElementId: link.source,
targetElementPosition, targetElementPosition,
targetElementId, targetElementId,
links: linksInner, links: linksInner,
nodes nodes,
}) });
if (newPaths.length != 0) { if (newPaths.length != 0) {
paths.push(...newPaths) paths.push(...newPaths);
} }
} }
} }
} }
return paths return paths;
} }
async function findDistance({ async function findDistance({
sourceElementId, sourceElementPosition, sourceElementId,
targetElementId, targetElementPosition, sourceElementPosition,
nodes, links targetElementId,
targetElementPosition,
nodes,
links,
}) { }) {
// This function gets all possible paths using findPaths // This function gets all possible paths using findPaths
// then orders them correctly in the for loop // then orders them correctly in the for loop
// (by flipping the distance to 1/distance when necessary) // (by flipping the distance to 1/distance when necessary)
// and then gets the array of weights for the different paths. // and then gets the array of weights for the different paths.
console.log(`findDistance@findPaths.js from ${sourceElementPosition} to ${targetElementPosition}`) console.log(
`findDistance@findPaths.js from ${sourceElementPosition} to ${targetElementPosition}`
);
let maxLengthOfPath = Math.abs(sourceElementPosition - targetElementPosition) let maxLengthOfPath = Math.abs(sourceElementPosition - targetElementPosition);
let paths = await findPaths({ let paths = await findPaths({
sourceElementId, sourceElementPosition, sourceElementId,
targetElementId, targetElementPosition, sourceElementPosition,
links, nodes, targetElementId,
maxLengthOfPath, pathSoFar: [] targetElementPosition,
links,
nodes,
maxLengthOfPath,
pathSoFar: [],
}); });
let weights = [] let weights = [];
for (let path of paths) { for (let path of paths) {
let currentSource = sourceElementId let currentSource = sourceElementId;
let weight = 1 let weight = 1;
for (let element of path) { for (let element of path) {
let distance = 0 let distance = 0;
if (element.source == currentSource) { if (element.source == currentSource) {
distance = element.distance distance = element.distance;
currentSource = element.target currentSource = element.target;
} else if (element.target == currentSource) { } else if (element.target == currentSource) {
distance = 1 / Number(element.distance) distance = 1 / Number(element.distance);
currentSource = element.source currentSource = element.source;
} }
weight = weight * distance weight = weight * distance;
} }
weights.push(weight) weights.push(weight);
} }
return weights return weights;
} }
async function findDistancesForAllElements({ nodes, links }) { async function findDistancesForAllElements({ nodes, links }) {
// Simple wrapper function around findDistance // Simple wrapper function around findDistance
// Needs to find the reference point first // Needs to find the reference point first
console.log("findDistancesForAllElements@findPaths.js") console.log("findDistancesForAllElements@findPaths.js");
/* Get or build reference element */ /* Get or build reference element */
let referenceElements = nodes.filter(x => x.isReferenceValue) let referenceElements = nodes.filter((x) => x.isReferenceValue);
let midpoint = Math.round(nodes.length / 2) let midpoint = Math.round(nodes.length / 2);
let referenceElement = referenceElements.length > 0 ? referenceElements[0] : nodes[midpoint] let referenceElement =
console.log(`referenceElement.position: ${referenceElement.position}`) referenceElements.length > 0 ? referenceElements[0] : nodes[midpoint];
console.log(`referenceElement.position: ${referenceElement.position}`);
/* Get distances. */ /* Get distances. */
let distances = nodes.map(node => { let distances = nodes.map((node) => {
if (node.isReferenceValue || (node.id == referenceElement.id)) { if (node.isReferenceValue || node.id == referenceElement.id) {
return [1] return [1];
} else { } else {
console.log("node") console.log("node");
console.log(node) console.log(node);
let distance = findDistance({ let distance = findDistance({
sourceElementId: referenceElement.id, sourceElementId: referenceElement.id,
sourceElementPosition: referenceElement.position, sourceElementPosition: referenceElement.position,
@ -192,59 +222,70 @@ async function findDistancesForAllElements({ nodes, links }) {
targetElementPosition: node.position, targetElementPosition: node.position,
nodes: nodes, nodes: nodes,
links: links, links: links,
}) });
return distance return distance;
} }
}) });
distances = await Promise.all(distances) distances = await Promise.all(distances);
return distances return distances;
} }
export async function buildRows({ isListOrdered, orderedList, listOfElements, links, rows, setTableRows }) { export async function buildRows({
console.log("buildRows@findPaths.js") isListOrdered,
orderedList,
listOfElements,
links,
rows,
setTableRows,
}) {
console.log("buildRows@findPaths.js");
// This function is used in pages/comparisonView.js to create the rows that will be displayed. // This function is used in pages/comparisonView.js to create the rows that will be displayed.
// it is in there because it needs to be deployed after isListOrdered becomes true, // it is in there because it needs to be deployed after isListOrdered becomes true,
// and using an useEffect inside CreateTable was too messy. // and using an useEffect inside CreateTable was too messy.
if (isListOrdered && !(orderedList.length < listOfElements.length) && rows.length == 0) { if (
let nodes = [] isListOrdered &&
let positionDictionary = ({}) !(orderedList.length < listOfElements.length) &&
rows.length == 0
) {
let nodes = [];
let positionDictionary = {};
orderedList.forEach((id, pos) => { orderedList.forEach((id, pos) => {
nodes.push({ ...listOfElements[id], position: pos }) nodes.push({ ...listOfElements[id], position: pos });
positionDictionary[id] = pos positionDictionary[id] = pos;
}) });
links = links.map(link => ({ links = links.map((link) => ({
...link, ...link,
sourceElementPosition: positionDictionary[link.source], sourceElementPosition: positionDictionary[link.source],
targetElementPosition: positionDictionary[link.target] targetElementPosition: positionDictionary[link.target],
})) }));
let distances = await findDistancesForAllElements({ nodes, links }) let distances = await findDistancesForAllElements({ nodes, links });
rows = nodes.map((element, i) => ({ rows = nodes.map((element, i) => ({
id: numToAlphabeticalString(element.position), id: numToAlphabeticalString(element.position),
position: element.position, position: element.position,
name: element.name, name: element.name,
distances: distances[i] distances: distances[i],
})) }));
console.log(rows) console.log(rows);
setTableRows(rows) setTableRows(rows);
} }
} }
export function CreateTable({ tableRows }) { export function CreateTable({ tableRows }) {
/* This function receives a list of rows, and displays them nicely. */ /* This function receives a list of rows, and displays them nicely. */
function abridgeArrayAndDisplay(array) { function abridgeArrayAndDisplay(array) {
let newArray let newArray;
let formatForDisplay let formatForDisplay;
if (array.length > 10) { if (array.length > 10) {
newArray = array.slice(0, 9) newArray = array.slice(0, 9);
formatForDisplay = newArray.map(d => formatLargeOrSmall(d)) formatForDisplay = newArray.map((d) => formatLargeOrSmall(d));
formatForDisplay[9] = "..." formatForDisplay[9] = "...";
} else { } else {
newArray = array newArray = array;
formatForDisplay = newArray.map(d => formatLargeOrSmall(d)) formatForDisplay = newArray.map((d) => formatLargeOrSmall(d));
} }
let result = JSON.stringify(formatForDisplay, null, 2).replaceAll(`"`, "") let result = JSON.stringify(formatForDisplay, null, 2).replaceAll(`"`, "");
return result return result;
} }
return ( return (
<div> <div>
@ -263,7 +304,8 @@ export function CreateTable({ tableRows }) {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{tableRows.map(row => <tr key={row.id}> {tableRows.map((row) => (
<tr key={row.id}>
<td className="">{row.id}</td> <td className="">{row.id}</td>
<td>&nbsp;&nbsp;&nbsp;</td> <td>&nbsp;&nbsp;&nbsp;</td>
<td className="">{row.position}</td> <td className="">{row.position}</td>
@ -272,14 +314,15 @@ export function CreateTable({ tableRows }) {
<td>&nbsp;&nbsp;&nbsp;</td> <td>&nbsp;&nbsp;&nbsp;</td>
<td className="">{abridgeArrayAndDisplay(row.distances)}</td> <td className="">{abridgeArrayAndDisplay(row.distances)}</td>
<td>&nbsp;&nbsp;&nbsp;</td> <td>&nbsp;&nbsp;&nbsp;</td>
<td className="">{formatLargeOrSmall(avg(row.distances))}</td> <td className="">
{formatLargeOrSmall(geomMean(row.distances))}
</td>
</tr> </tr>
)} ))}
</tbody> </tbody>
</table> </table>
</div> </div>
) );
} }
/* Testing */ /* Testing */
@ -301,3 +344,4 @@ console.log(JSON.stringify(paths, null, 2))
let distances = findDistance({sourceElementId:2, targetElementId:4, links, nodes}) let distances = findDistance({sourceElementId:2, targetElementId:4, links, nodes})
console.log(distances) console.log(distances)
*/ */

View File

@ -1,6 +1,11 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import * as d3 from 'd3'; import * as d3 from "d3";
import { toLocale, truncateValueForDisplay, numToAlphabeticalString, formatLargeOrSmall } from "./utils.js" import {
toLocale,
truncateValueForDisplay,
numToAlphabeticalString,
formatLargeOrSmall,
} from "./utils.js";
let getlength = (number) => number.toString().length; let getlength = (number) => number.toString().length;
@ -9,41 +14,39 @@ export function removeOldSvg() {
} }
function drawGraphInner({ nodes, links }) { function drawGraphInner({ nodes, links }) {
// List of node ids for convenience // List of node ids for convenience
var nodeids = nodes.map(node => node.id) var nodeids = nodes.map((node) => node.id);
var positionById = {} var positionById = {};
nodeids.forEach((nodeid, i) => positionById[nodeid] = i) nodeids.forEach((nodeid, i) => (positionById[nodeid] = i));
console.log("NodeIds/positionById") console.log("NodeIds/positionById");
console.log(nodeids) console.log(nodeids);
console.log(positionById) console.log(positionById);
// Calculate the dimensions // Calculate the dimensions
// let margin = { top: 0, right: 30, bottom: 20, left: 30 }; // let margin = { top: 0, right: 30, bottom: 20, left: 30 };
// let width = 900 - margin.left - margin.right; // let width = 900 - margin.left - margin.right;
let initialWindowWidth = window.innerWidth let initialWindowWidth = window.innerWidth;
let margin = { top: 0, right: 10, bottom: 30, left: 10 }; let margin = { top: 0, right: 10, bottom: 30, left: 10 };
let width = initialWindowWidth*0.7 - margin.left - margin.right; let width = initialWindowWidth * 0.8 - margin.left - margin.right;
var x = d3.scalePoint() var x = d3.scalePoint().range([0, width]).domain(nodeids);
.range([0, width])
.domain(nodeids)
let heights = links.map(link => { let heights = links.map((link) => {
let start = x(positionById[link.source]) let start = x(positionById[link.source]);
let end = x(positionById[link.target]) let end = x(positionById[link.target]);
return Math.abs(start - end) / 2 + 70 // Magic constant. return Math.abs(start - end) / 2 + 70; // Magic constant.
}) });
console.log(heights) console.log(heights);
let maxheight = Math.max(...heights) let maxheight = Math.max(...heights);
let height = maxheight - margin.top - margin.bottom; let height = maxheight - margin.top - margin.bottom;
console.log(`height: ${height}`) console.log(`height: ${height}`);
// Build the d3 graph // Build the d3 graph
removeOldSvg() removeOldSvg();
var svg = d3.select("#graph") var svg = d3
.select("#graph")
.append("svg") .append("svg")
.attr("width", width + margin.left + margin.right) .attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom) .attr("height", height + margin.top + margin.bottom)
@ -52,17 +55,18 @@ function drawGraphInner({ nodes, links }) {
// A linear scale to position the nodes on the X axis // A linear scale to position the nodes on the X axis
// Add the circle for the nodes // Add the circle for the nodes
svg svg
.selectAll("mynodes") .selectAll("mynodes")
.data(nodes) .data(nodes)
.enter() .enter()
.append("circle") .append("circle")
.attr("cx", function (d) { return (x(d.id)) }) .attr("cx", function (d) {
return x(d.id);
})
.attr("cy", height - 30) .attr("cy", height - 30)
.attr("r", 8) .attr("r", 8)
.style("fill", "#69b3a2") .style("fill", "#69b3a2");
// And give them a label // And give them a label
svg svg
@ -70,76 +74,98 @@ function drawGraphInner({ nodes, links }) {
.data(nodes) .data(nodes)
.enter() .enter()
.append("text") .append("text")
.attr("x", function (d) { return (x(d.id)) }) .attr("x", function (d) {
return x(d.id);
})
.attr("y", height - 10) .attr("y", height - 10)
.text(function (d) { return numToAlphabeticalString(d.position) }) .text(function (d) {
.style("text-anchor", "middle") return numToAlphabeticalString(d.position);
})
.style("text-anchor", "middle");
// Add the links // Add the links
svg svg
.selectAll('mylinks') .selectAll("mylinks")
.data(links) .data(links)
.enter() .enter()
.append('path') .append("path")
.attr('d', function (d) { .attr("d", function (d) {
let start = x(d.source) let start = x(d.source);
// X position of start node on the X axis // X position of start node on the X axis
let end = x(d.target) let end = x(d.target);
// X position of end node // X position of end node
return ['M', return (
[
"M",
start, start,
height - 30, height - 30,
// the arc starts at the coordinate x=start, y=height-30 (where the starting node is) // the arc starts at the coordinate x=start, y=height-30 (where the starting node is)
'A', "A",
// This means we're gonna build an elliptical arc // This means we're gonna build an elliptical arc
(start - end) / 2, ',', (start - end) / 2,
",",
// Next 2 lines are the coordinates of the inflexion point. Height of this point is proportional with start - end distance // Next 2 lines are the coordinates of the inflexion point. Height of this point is proportional with start - end distance
(start - end) / 2, 0, 0, ',', (start - end) / 2,
start < end ? 1 : 0, end, ',', height - 30] 0,
0,
",",
start < end ? 1 : 0,
end,
",",
height - 30,
]
// We always want the arc on top. So if end is before start, putting 0 here turn the arc upside down. // We always want the arc on top. So if end is before start, putting 0 here turn the arc upside down.
.join(' '); .join(" ")
);
}) })
.style("fill", "none") .style("fill", "none")
.attr("stroke", "black") .attr("stroke", "black");
// labels for links // labels for links
svg svg
.selectAll('mylinks') .selectAll("mylinks")
.data(links) .data(links)
.enter() .enter()
.append("text") .append("text")
.attr("x", function (d) { .attr("x", function (d) {
let start = x(d.source) let start = x(d.source);
// X position of start node on the X axis // X position of start node on the X axis
let end = x(d.target) let end = x(d.target);
// X position of end node // X position of end node
return start + (end - start) / 2 //-4*getlength(d.distance) return start + (end - start) / 2; //-4*getlength(d.distance)
}) })
.attr("y", function (d) { .attr("y", function (d) {
let start = x(d.source) let start = x(d.source);
// X position of start node on the X axis // X position of start node on the X axis
let end = x(d.target) let end = x(d.target);
// X position of end node // X position of end node
return height - 32 - (Math.abs(start - end) / 2)//height-30 return height - 32 - Math.abs(start - end) / 2; //height-30
}) })
.text(function (d) { .text(function (d) {
return formatLargeOrSmall(Number(d.distance)) return formatLargeOrSmall(Number(d.distance));
// return (truncateValueForDisplay(Number(d.distance))) // return (truncateValueForDisplay(Number(d.distance)))
//return(Number(d.distance).toPrecision(2).toString()) //return(Number(d.distance).toPrecision(2).toString())
}) })
.style("text-anchor", "middle") .style("text-anchor", "middle");
} }
export function DrawGraph({ isListOrdered, orderedList, listOfElements, links }) { export function DrawGraph({
isListOrdered,
orderedList,
listOfElements,
links,
}) {
if (isListOrdered) { if (isListOrdered) {
let nodes = orderedList.map((id, pos) => ({ ...listOfElements[id], position: pos })) let nodes = orderedList.map((id, pos) => ({
...listOfElements[id],
position: pos,
}));
drawGraphInner({ nodes, links }); drawGraphInner({ nodes, links });
} }
return ( return (
<div> <div>
<div id="graph"> <div id="graph"></div>
</div>
</div> </div>
); );
} }

View File

@ -1,58 +1,69 @@
import crypto from "crypto" import crypto from "crypto";
export const hashString = (string) => crypto.createHash('md5').update(string).digest('hex'); export const hashString = (string) =>
const id = x => x crypto.createHash("md5").update(string).digest("hex");
export const transformSliderValueToActualValue = id const id = (x) => x;
export const transformSliderValueToPracticalValue = id export const transformSliderValueToActualValue = id;
export const transformSliderValueToPracticalValue = id;
export const _transformSliderValueToActualValue = value => 10 ** value //>= 2 ? Math.round(10 ** value) : Math.round(10 * 10 ** value) / 10 export const _transformSliderValueToActualValue = (value) => 10 ** value; //>= 2 ? Math.round(10 ** value) : Math.round(10 * 10 ** value) / 10
export const toLocale = x => Number(x).toLocaleString() export const toLocale = (x) => Number(x).toLocaleString();
export const truncateValueForDisplay = value => { export const truncateValueForDisplay = (value) => {
if (value > 10) { if (value > 10) {
return Number(Math.round(value).toPrecision(2)) return Number(Math.round(value).toPrecision(2));
} else if (value > 1) { } else if (value > 1) {
return Math.round(value * 10) / 10 return Math.round(value * 10) / 10;
} else if (value < 1) { } else if (value < 1) {
} }
} };
export const _transformSliderValueToPracticalValue = value => truncateValueForDisplay(transformSliderValueToActualValue(value)) export const _transformSliderValueToPracticalValue = (value) =>
truncateValueForDisplay(transformSliderValueToActualValue(value));
export function sleep(ms) { export function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
} }
export function numToAlphabeticalString(num) { export function numToAlphabeticalString(num) {
// https://stackoverflow.com/questions/45787459/convert-number-to-alphabet-string-javascript/45787487 // https://stackoverflow.com/questions/45787459/convert-number-to-alphabet-string-javascript/45787487
num = num + 1 num = num + 1;
var s = '', t; var s = "",
t;
while (num > 0) { while (num > 0) {
t = (num - 1) % 26; t = (num - 1) % 26;
s = String.fromCharCode(65 + t) + s; s = String.fromCharCode(65 + t) + s;
num = (num - t) / 26 | 0; num = ((num - t) / 26) | 0;
} }
return `#${s}` || undefined; return `#${s}` || undefined;
} }
export function formatLargeOrSmall(num) { export function formatLargeOrSmall(num) {
if (num > 1) { if (num > 1) {
return toLocale(truncateValueForDisplay(num)) return toLocale(truncateValueForDisplay(num));
} else if (num > 0) { } else if (num > 0) {
return num.toFixed(-Math.floor(Math.log(num) / Math.log(10)) + 1); return num.toFixed(-Math.floor(Math.log(num) / Math.log(10)) + 1);
} else if (num < -1) { } else if (num < -1) {
return num.toFixed(-Math.floor(Math.log(-num) / Math.log(10)) + 1); return num.toFixed(-Math.floor(Math.log(-num) / Math.log(10)) + 1);
} else { } else {
return toLocale(num)//return "~0" return toLocale(num); //return "~0"
} }
} }
const firstFewMaxMergeSortSequence = [0, 0, 1, 3, 5, 8, 11, 14, 17, 21, 25, 29, 33, 37, 41, 45, 49, 54, 59, 64, 69, 74, 79, 84, 89, 94, 99, 104, 109, 114, 119, 124, 129, 135, 141, 147, 153, 159, 165, 171, 177, 183, 189, 195, 201, 207, 213, 219, 225, 231, 237, 243, 249, 255, 261, 267, 273, 279, 285] const firstFewMaxMergeSortSequence = [
0, 0, 1, 3, 5, 8, 11, 14, 17, 21, 25, 29, 33, 37, 41, 45, 49, 54, 59, 64, 69,
74, 79, 84, 89, 94, 99, 104, 109, 114, 119, 124, 129, 135, 141, 147, 153, 159,
165, 171, 177, 183, 189, 195, 201, 207, 213, 219, 225, 231, 237, 243, 249,
255, 261, 267, 273, 279, 285,
];
export function maxMergeSortSteps(n) { export function maxMergeSortSteps(n) {
if (n < firstFewMaxMergeSortSequence.length) { if (n < firstFewMaxMergeSortSequence.length) {
return firstFewMaxMergeSortSequence[n] return firstFewMaxMergeSortSequence[n];
} else { } else {
return maxMergeSortSteps(Math.floor(n / 2)) + maxMergeSortSteps(Math.ceil(n / 2)) + n - 1 return (
maxMergeSortSteps(Math.floor(n / 2)) +
maxMergeSortSteps(Math.ceil(n / 2)) +
n -
1
);
} }
} }
@ -61,18 +72,23 @@ export function expectedNumMergeSortSteps(n) {
// n-2 for each step, so (n-2) + (n-2)/2 + (n-2)/4 + ... // n-2 for each step, so (n-2) + (n-2)/2 + (n-2)/4 + ...
// ~ 2*(n-2) -1 = 2*n - 3 // ~ 2*(n-2) -1 = 2*n - 3
if (n == 0) { if (n == 0) {
return 0 return 0;
} else if (n == 1) { } else if (n == 1) {
return 0 return 0;
} else if (n == 2) { } else if (n == 2) {
return 1 return 1;
} else if (n == 3) { } else if (n == 3) {
return 2 return 2;
} else { } else {
return Math.ceil((n ** 2) / (n + 2)) + expectedNumMergeSortSteps(Math.ceil(n / 2)) return (
Math.ceil(n ** 2 / (n + 2)) + expectedNumMergeSortSteps(Math.ceil(n / 2))
);
} }
} }
export const avg = arr => arr.reduce((a, b) => (a + b), 0) / arr.length export const avg = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
export const increasingList = (n) => Array.from(Array(n).keys()) export const geomMean = (arr) =>
arr.reduce((a, b) => a * b, 1) ^ (1 / arr.length);
export const increasingList = (n) => Array.from(Array(n).keys());