Published unlisted
Edited
Feb 26, 2021
2 stars
Insert cell
Insert cell
mutable deck = d3.cross(
["clubs", "diamonds", "hearts", "spades"],
[..."123456789JQKA"]
).map(([suit, value]) => ({suit, value}))
Insert cell
Button([["Sort", sort], ["Shuffle", shuffle]])
Insert cell
viewof selected = Table(deck, {
// Allow the table’s selection to be empty.
required: false,
// In Observable, “this” refers to the previous value of this cell.
// It can be tricky to use correctly and so is generally discouraged,
// but it’s convenient here since we want to preserve the Table’s
// selection when the mutable deck value changes. Since this is a
// view cell, “this” refers to the Table input, and hence we can
// access the checked cards as this.value.
value: this && this.value
})
Insert cell
function shuffle() {

// Convert the selection to a set for efficiency.
const selection = new Set(selected);

// Initialize the shuffled deck. Any checked cards are assigned their spot,
// while any unchecked cards are initially undefined and will be populated
// after shuffling.
const shuffled = mutable deck.map(d => selection.has(d) ? d : undefined);

// Shuffle the unchecked cards, weaving them into the available
// slots in the partial deck already containing checked cards.
let i = 0;
for (const d of d3.shuffle(mutable deck.filter(d => !selection.has(d)))) {
while (shuffled[i] !== undefined) ++i;
shuffled[i] = d;
}

// Assign the new mutable deck, triggering the table to be redrawn.
mutable deck = shuffled;
}
Insert cell
function sort() {
mutable deck = d3.sort(mutable deck, order);
}
Insert cell
function order(a, b) {
return d3.ascending(a.suit, b.suit) || d3.ascending(a.value, b.value);
}
Insert cell
import {Button, Table, html} from "@observablehq/inputs"
Insert cell
d3 = require("d3-array@2")
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