Published
Edited
Dec 4, 2020
5 stars
Insert cell
Insert cell
Insert cell
Insert cell
wholes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Insert cell
Insert cell
function filter(predicateFn, array) {
if (length(array) === 0) return [];
const firstItem = head(array);
const filteredFirst = predicateFn(firstItem) ? [firstItem] : [];
return concat(filteredFirst, filter(predicateFn, tail(array)));
}
Insert cell
Insert cell
function isEven(n) {
return n % 2 === 0;
}
Insert cell
evens = filter(isEven, wholes)
Insert cell
Insert cell
odds = filter(n => {
return !isEven(n);
}, wholes)
Insert cell
Insert cell
greaterThanFour = filter(n => n > 4, wholes)
Insert cell
Insert cell
function isPrime(n) {
if (n <= 1) return false;
const wholes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const possibleFactors = filter(m => m > 1 && m < n, wholes);
const factors = filter(m => n % m === 0, possibleFactors);
return factors.length === 0 ? true : false;
}
Insert cell
primes = filter(isPrime, wholes)
Insert cell
Insert cell
Insert cell
function map(fn, array) {
if (length(array) === 0) return [];
return [fn(head(array))].concat(map(fn, tail(array)));
}
Insert cell
doubled = map(n => n * 2, wholes)
Insert cell
Insert cell
halved = map(n => n / 2, wholes)
Insert cell
Insert cell
Insert cell
fizzBuzz = map(n => {
const fizzed = n % 3 === 0 ? 'fizz' : '';
const buzzed = n % 5 === 0 ? 'buzz' : '';
return fizzed || buzzed ? fizzed + buzzed : n;
}, wholes)
Insert cell
fizzBuzz
Insert cell
Insert cell
Insert cell
function reduce(reducerFn, initialValue, array) {
if (length(array) === 0) return initialValue;
const newInitialValue = reducerFn(initialValue, head(array));
return reduce(reducerFn, newInitialValue, tail(array));
}
Insert cell
Insert cell
sum = reduce(
(accumulator, value) => {
return accumulator + value;
},
0,
wholes
)
Insert cell
Insert cell
max = reduce(
(acc, val) => {
return val > acc ? val : acc;
},
0,
[7, 1, 3, 5, 6, 2, 8, 10, 0, 4, 9]
)
Insert cell
Insert cell
Insert cell
Insert cell
// Concatenate two arrays into a new single array
function concat(array1, array2) {
return array1.concat(array2);
}
Insert cell
// Return the number of items in an array
function length(array) {
return array.length;
}
Insert cell
Insert cell
// Return the rest of an array after the first item
function tail(array) {
return array.slice(1);
}
Insert cell
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