Public
Edited
Apr 2, 2023
1 star
Insert cell
Insert cell
Insert cell
// early version by ChatGPT that works
function splitNumberJS(n) {
const s = Math.ceil(Math.sqrt(n));
const factors = Array.from({ length: s - 1 }, (_, i) => s - i);
const factor = factors.find(f => n % f === 0);
return factor ? [factor, n/factor] : [1, n];
}
Insert cell
tabularize(splitNumberJS)(d3.range(36).map(splitNumberJS))
Insert cell
// Martien’s take on the Ramda equivalent of splitNumberJS
//
// split number in two factors closest to each other
// that is, aspect ratio as close to 1 as possible
// e.g. splitter(12) -> [4,3]
// e.g. splitter(16) -> [4,4]
splitNumberRamda = (n) => {
const t = n ** 0.5; // t = √t;
const r = R.pipe(
R.range(1), // potential factors of n in ascending order
R.findLast( // from back to front:
(f) => !(n % f)), // find first, thus largest factor that divides n evenly
)
(((t|0) + (t > (t|0)) + 1)) // t += 1 if n != square (i.e. when t != whole, i.e. t > (t|0))
|| 1; // or return 1 when no divider is found
return [r, n / r];
}
Insert cell
tabularize(splitNumberRamda)(d3.range(36).map(splitNumberRamda))
Insert cell
Insert cell
Insert cell
tabularize = (splitter) => (list) =>
R.pipe(
R.splitEvery(splitter(list.length)[0]), // take first row’s length
R.transpose, // so you can read the table row by row isnted of column by column
htmlTable, // convert to HTML
)
(list)
Insert cell
htmlTable = (data) => {
const row = (row, r) => `<tr align="right"><td style="font-weight:bold">${r * row.length}</td>${row.map(cell).join("")}</tr>`;
const cell = (c) => `<td>${c}</td>`;
const head = (_, c) => `<th style="text-align:right;">${c}</th>`;
const h = `<tr><th/>${data[0].map(head).join("")}</tr>`;
const vv = h + data.map(row).join("")
return md`<table style="font-family:monospace;">${vv}</table>`;
}
Insert cell
R = require("ramda")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more