Published
Edited
Jan 10, 2020
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
// Here are the kids...
kids = [{name:"Abigail", isNaughty:false},
{name:"Ben", isNaughty:false},
{name:"Clara", isNaughty:true},
{name:"David", isNaughty:false},
{name:"Emily", isNaughty:true},
{name:"Fred", isNaughty:false},
{name:"Gloria", isNaughty:false},
{name:"Harry", isNaughty:false},
{name:"Ingrid", isNaughty:true},
{name:"Jack", isNaughty:false}]

Insert cell
// Find the good ones...
kids.filter(function(k) {
return !k.isNaughty;
})
Insert cell
Insert cell
function(k) {
return !k.isNaughty;
}

Insert cell
Insert cell
k => !k.isNaughty
Insert cell
Insert cell
// Count the good ones...
kids.filter(k => !k.isNaughty).length
Insert cell
Insert cell
(acc,k) => acc + !k.isNaughty
Insert cell
Insert cell
naughty_and_nice = kids.reduce((acc,k) => {
acc.nice += !k.isNaughty;
acc.naughty += k.isNaughty;
return acc;
}, {naughty:0, nice:0})
Insert cell
Insert cell
function Kid1(pName) {
this.name = pName || "";

setInterval(function are_you_nice() {
// Randomly choose whether the kid is naughty or nice
this.isNaughty = !!(Math.trunc(Math.random()*10) % 2);
}, 1000)
}
Insert cell
new Kid1("Kim")
Insert cell
Insert cell
function Kid2(pName) {
this.name = pName || "";
var that = this;
setInterval(function are_you_nice() {
// Randomly choose whether the kid is naughty or nice
that.isNaughty = !!(Math.trunc(Math.random()*10) % 2);
}, 1000);
}
Insert cell
Insert cell
Insert cell
function Kid3(pName) {
this.name = pName || "";
// The function passed to setInterval is now an arrow function
// Therefore, the 'this' inside the arrow function now refers to the same 'this' seen in the Kid3
// constructor. In other words, we are now using a 'lexical' this
setInterval(() => this.isNaughty = !!(Math.trunc(Math.random()*10) % 2), 1000)
}
Insert cell
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