HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
const roads = ["Alice's House-Bob's House", "Alice's House-Cabin", "Alice's House-Post Office", "Bob's House-Town Hall", "Daria's House-Ernie's House", "Daria's House-Town Hall", "Ernies' House-Grete's House", "Grete's House-Farm", "Grete's House-Shop", "Marketplace-Farm", "Marketplace-Post Office", "Marketplace-Shop", "Marketplace-Town Hall", "Shop-Town Hall"];
function buildGraph(edges) {
let graph = Object.create(null);
function addEdge(from, to) {
if(graph[from] == null) {
graph[from] = [to];
} else {
graph[from].push(to);
}
}
for (let [from, to] of edges.map(r => r.split("-"))) {
addEdge(from, to);
addEdge(to, from);
}
return graph;
}
const roadGraph = buildGraph(roads);
class VillageState {
constructor(place, parcels) {
this.place = place;
this.parcels = parcels;
}
move(destination) {
// Check if the move is valid, otherwise return old state.
if(!roadGraph[this.place].includes(destination)) {
return this;
} else {
let parcels = this.parcels.map(p => {
// If the parcel's location is not equal to the robot's, the parcel won't move next round. (Parcel is not yet picked up)
if(p.place != this.place) return p;
// If the parcel's location is equal to the robot's, the parcel's next location will be the robot's destination. (Parcel is picked up)
return { place: destination, address: p.address }
// Filter out the parcel's who's current location have been updated to their destination address (Parcel is delivered)
}).filter(p => p.place != p.address);
return new VillageState(destination, parcels);
}
}
}
// Takes a VillageState (starting location and parcels (with a location and a destination)), a robot and a memory
function runRobot(state, robot, memory) {
for (let turn = 0;; turn++) {
if (state.parcels.length == 0) {
console.log(`Done in ${turn} turns`);
return turn;
}
let action = robot(state, memory);
state = state.move(action.direction);
memory = action.memory;
console.log(`Moved to ${action.direction}`);
}
}
function randomPick(array) {
let choice = Math.floor(Math.random() * array.length);
return array[choice];
}
function randomRobot(state) {
return {direction: randomPick(roadGraph[state.place])};
}
VillageState.random = function(parcelCount = 5) {
let parcels = [];
for (let i = 0; i < parcelCount; i++) {
let address = randomPick(Object.keys(roadGraph));
let place;
do {
place = randomPick(Object.keys(roadGraph));
} while (place == address);
parcels.push({place, address});
}
return new VillageState("Post Office", parcels);
};
// runRobot(VillageState.random(), randomRobot);
const mailRoute = [
"Alice's House", "Cabin", "Alice's House", "Bob's House", "Town Hall", "Daria's House", "Ernie's House", "Grete's House", "Shop", "Grete's House", "Farm", "Marketplace", "Post Office"
];
function routeRobot(state, memory) {
if(memory.length == 0) {
memory = mailRoute;
}
return {direction: memory[0],
memory: memory.slice(1)};
}
// runRobot(VillageState.random(), routeRobot);
function findRoute(graph, from, to) {
// Start with a work list of places to explore next [at]
// along with the route that got us there (route)
let work = [{at: from, route: []}];
// Loop through the work list (it will grow
// inside the loop)
for (let i=0; i < work.length; i++) {
// Take the current location (at) and the current route
let {at, route} = work[i];
// For the current location, loop through the
// possible next destinations
for (let place of graph[at]) {
// If one of the destinations is the target, add it to
// the route and return the route.
if (place == to) return route.concat(place);
// If the target is not found, and if we haven't
// looked at this place before, we add it to the
// list.
if(!work.some(w => w.at == place)) {
work.push({at: place, route: route.concat(place)});
}
}
}
}
function goalOrientedRobot({place, parcels}, route) {
if (route.length == 0) {
let parcel = parcels[0];
if(parcel.place != place) {
route = findRoute(roadGraph, place, parcel.place);
} else {
route = findRoute(roadGraph, place, parcel.address);
}
}
return {direction: route[0], memory: route.slice(1)}
}
runRobot(VillageState.random(), goalOrientedRobot, []);
function compareRobots(robotOne, robotTwo) {
robotOneResults = [];
robotTwoResults = [];
for (let i=0; i<100; i++) {
let villageState = VillageState.random();
robotOneResults.push(runRobot(villageState, robotOne, []));
robotTwoResults.push(runRobot(villageState, robotTwo, []));
}
console.log(`Robot 1: ${getAverage(robotOneResults)}`);
console.log(`Robot 2: ${getAverage(robotTwoResults)}`);
}
function getAverage(inputArray) {
return inputArray.reduce((acc, c) => (acc + c)) / inputArray.length;
}
// compareRobots(goalOrientedRobot, randomRobot);
function nearestParcelRobot({place, parcels}, route) {
if (route.length == 0) {
let parcel = parcels[getNearestParcelIndex(place, parcels)];
if(parcel.place != place) {
route = findRoute(roadGraph, place, parcel.place);
} else {
route = findRoute(roadGraph, place, parcel.address);
}
}
return {direction: route[0], memory: route.slice(1)}
}
function getNearestParcelIndex(currentLocation, parcels) {
let nearestParcelLocation = '';
let shortestRouteSoFar = 99;
let index = -1;
for (let parcel of parcels) {
index++;
route = findRoute(roadGraph, currentLocation, parcel.place);
if (route.length < shortestRouteSoFar) {
shortestRouteSoFar = route.length;
console.log(shortestRouteSoFar);
indexForShortestRoute = index;
}
}
return indexForShortestRoute;
}
// Notes
// Map the parcels array onto a new array of routes which includes a route property which we bind to the result of findRoute for that parcel's location
// In the same element in the new array, track whether the parcel has been picked up and when it hasn't, give that option a 0.5 score.
// Add the length of the route to the score and choose the parcel with the lowest score.
function lazyRobot({place, parcels}, route) {
if (route.length == 0) {
// Describe a route for every parcel
let routes = parcels.map(parcel => {
if (parcel.place != place) {
return {route: findRoute(roadGraph, place, parcel.place),
pickUp: true};
} else {
return {route: findRoute(roadGraph, place, parcel.address),
pickUp: false};
}
});
// This determines the precedence a route gets when choosing.
// Route length counts negatively, routes that pick up a package
// get a small bonus.
function score({route, pickUp}) {
return (pickUp ? 0.5 : 0) - route.length;
}
route = routes.reduce((a, b) => score(a) > score(b) ? a : b).route;
}
return {direction: route[0], memory: route.slice(1)};
}
// compareRobots(nearestParcelRobot, lazyRobot);
class PGroup {
constructor(inputArray) {
this.members = inputArray;
}
add(value) {
if (this.has(value)) return this;
return new PGroup([...this.members, value]);
}
delete(value) {
if (!this.has(value)) return this;
return new PGroup(this.members.filter(x => x !== value));
}
has(value) {
return this.members.includes(value);
}
}
PGroup.empty = new PGroup([]);
let a = PGroup.empty.add("a");
let ab = a.add("b");
let b = ab.delete("a");
console.log(b.has("b"));
// → true
console.log(a.has("b"));
// → false
console.log(b.has("a"));
// → false
Also see: Tab Triggers