Skip to content

Instantly share code, notes, and snippets.

@zachvictor
zachvictor / compactify.js
Last active October 11, 2022 22:19
JSON stringify function that compacts numeric arrays, putting brackets and values on the same line
function compactify(ugly) {
// Step 1: JSON stringify with indentation (4 spaces)
const first_pass = JSON.stringify(JSON.parse(ugly), null, 4)
// Step 2: Put comma-sep. numbers on same line
const comma_num_newline_ptn = /,\n +((\d\.)?\d+)/g
const num_same_line = first_pass.replace(comma_num_newline_ptn, ', $1')
// Step 3: Put flat arrays on same line
const flat_array_ptn = /\[\n\s+(([\d.]+, )+[\d.]+)\n\s+\]/g