Public
Edited
Jan 29, 2023
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)
// TODO your code goes here
}
Insert cell
evens = filter(isEven, wholes)
Insert cell
Insert cell
odds = filter(n => {
return (n%2!=0)
// TODO your code goes here
}, wholes)
Insert cell
Insert cell
greaterThanFour = filter(
(n) => {return n>4}, // TODO replace this line
wholes
)
Insert cell
Insert cell
function isPrime(n) {
if(n==0 || n==1) return false;
for(let idx = 2;idx<=(n/2);idx++){
if(n%idx==0) return false;
}
return true;
// TODO your code goes here
}
Insert cell
primes = filter(isPrime, wholes)
Insert cell
Insert cell
Insert cell
function map(fn, array) {
if (length(array) === 0) return [];
const mappedFirst = [fn(head(array))];
return concat(mappedFirst,map(fn,tail(array)));
// TODO your code goes here
}
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 => {
if(n%3==0 && n%5==0) return "fizzbuzz";
else if(n%3==0) return "fizz";
else if(n%5==0) return "buzz";
else return n;
// TODO your code goes here
}, 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;
// TODO your code here
},
0,
wholes
)
Insert cell
Insert cell
max = reduce(
(prevMax,current) => {
if(current>prevMax) return current;
else return prevMax;
}, // TODO replace this reducerFn
-1, // TODO replace this initialValue
[7, 1, 3, 5, 6, 2, 8, 10, 0, 4, 9]
)
Insert cell
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