JSFiddle - React, Tailwind, and code Playground
HTML
<div id="output"></div>
CSS
#output {
font-family: monospace;
}
JavaScript
"use strict";
// bs is an array of three-element arrays containing
// left x coordinate, height and right x coordinate
function skyline(bs) {
// returns the height of tallest building
// covering coordinate x
const height = function(x) {
// 0 is the default value in case
// there are no buildings at x
const candidates = [0];
// go through the list of all buildings
// (note that we access bs from outside
// the scope of height())
for (let b of bs) {
const x1 = b[0];
const h = b[1];
const x2 = b[2];
if (x >= x1 && x < x2) {
candidates.push(h);
}
};
return Math.max(...candidates);
};
// xs is the collection of previously processed points
// b is a three-element array (tuple in the
// original Haskell code)
const add_endpoints = function(xs, b) {
const x1 = b[0];
const h = b[1];
const x2 = b[2];
const left = [x1, height(x1)];
const right = [x2, height(x2)];
// copy xs to avoid modifying it in place
const updated = xs.slice();
updated.push(left);
updated.push(right);
return updated;
};
var endpoints = [];
// foldl applies a function to each element
// of a collection and passes the intermediate
// result to the next application
for (const b of bs) {
endpoints = add_endpoints(endpoints, b);
}
// sort endpoints by the x coordinate
endpoints.sort(function(a, b) {
if (a[0] < b[0]) {
return -1;
} else if (a[0] > b[0]) {
return 1;
}
return 0;
});
return endpoints;
}
const input = [[1,11,5],[2,6,7],[3,13,9],[12,7,16],[14,3,25],[19,18,22],[23,13,29],[24,4,28]];
const output = skyline(input);
// transform nested arrays to string
const tuples = [];
for (let t of output) {
tuples.push("(" + t.join(",") + ")");
}
const outputStr = "[" + tuples.join(",") + "]";
document.getElementById("output").innerHTML = outputStr;