Public
Edited
Jan 3, 2024
Insert cell
Insert cell
function greetSplit(lastCommaFirst) {
const first = lastCommaFirst.split(',')[1].trim();
const last = lastCommaFirst.split(',')[0].trim();

console.log(`Hello ${first} ${last}!`)
}
Insert cell
function observableGreetSplit(lastCommaFirst) {
const first = combineLatest(lastCommaFirst, (lastCommaFirst) => lastCommaFirst.split(',')[1].trim());
const last = combineLatest(lastCommaFirst, (lastCommaFirst) => lastCommaFirst.split(',')[0].trim());

const greetingSplit = combineLatest(first, last, (first, last) => `Hello ${first} ${last}!`);
greetingSplit.subscribe((greetingSplit) => console.log(greetingSplit))
}
Insert cell
Insert cell
function signalGreetSplit(lastCommaFirst) {
const first = createMemo(() => lastCommaFirst().split(',')[1].trim());
const last = createMemo(() => lastCommaFirst().split(',')[0].trim());

const greetingSplit = createMemo(() => `Hello ${first()} ${last()}!`);

// TODO: not sure if we're going to do this yet... also this will be destroyed when it ends right?
createEffect(() => console.log(greetingSplit()))
}
Insert cell
Insert cell
currentSources = []
Insert cell
function createMemo(f) {
}
Insert cell
// An implementation of the observer pattern
class Observable {
constructor(initialValue) {
this._value = initialValue;
this.observers = [];
}

read() {
/* NEW! */
currentSources.push(this);
return this._value;
}

write(newValue) {
if (newValue !== this._value) {
this._value = newValue;
this.notifyObservers();
}
}

// Method to add an observer
subscribe(observer) {
this.observers.push(observer);
}

// Method to notify all observers about the value change
notifyObservers() {
this.observers.forEach(observer => observer(this._value));
}
}
Insert cell
function combineLatest(...inputs) {
const observables = inputs.slice(0, -1);
const fn = inputs[inputs.length - 1];

/* NEW! */
// store the latest value for each observable
let latestValues = observables.map(obs => obs.read());

// initialize a new output observable
const obs = new Observable(fn(...latestValues));

// every time an observable changes...
observables.forEach((observable, index) => {
observable.subscribe((value) => {
/* NEW! */
// push the update to latestValues
latestValues[index] = value;

// update the output observable
obs.write(fn(...latestValues));
});
});

return obs;
}
Insert cell
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