Here's how we might approach the problem using functional programming.
Our first module will be the Person
module. First we create the ability to construct -
- a
person
, from a first
, last
, and place
- a
greeting
string, using a person as input
// Person.js
const person = (first, last, place) =>
({ first, last, place }) // construct a person
const greeting = (p = {}) =>
`hello my name is ${p.first} ${p.last}, i am from ${p.place}.` // construct greeting
export { person, greeting }
Now let's begin our Main
module; the program to run. Along the way we imagine an new module, Arr
, as a better version of JavaScript's Array
-
// Main.js
import { person, greeting } from "./Person"
import { map } from "./Arr"
const firstNames = // [ ... ]
const lastNames = // [ ... ]
const places = // [ ... ]
const people =
map(person, firstNames, lastNames, places) // TODO: implement map
for (const p of people) // for each person, p,
console.log(greeting(p)) // display greeting for p
// hello my name is Jon Snow, i am from The Wall.
// hello my name is Arya Stark, i am from Winterfell.
// hello my name is Jamie Lannister, i am from Kings Landing.
Finally implement the Arr
module -
// Arr.js
const isEmpty = (t = []) =>
t.length === 0
const first = (t = []) =>
t[0]
const rest = (t = []) =>
t.slice(1)
const map = (f, ...ts) =>
ts.some(isEmpty)
? []
: [ f(...ts.map(first))
, ...map(f, ...ts.map(rest))
]
export { isEmpty, first, rest, map }
Everything is done! Expand the snippet below to verify the result in your browser -
const isEmpty = (t = []) =>
t.length === 0
const first = (t = []) =>
t[0]
const rest = (t = []) =>
t.slice(1)
const map = (f, ...ts) =>
ts.some(isEmpty)
? []
: [ f(...ts.map(first))
, ...map(f, ...ts.map(rest))
]
const person = (first, last, place) =>
({ first, last, place })
const greeting = (p = {}) =>
`hello my name is ${p.first} ${p.last}, i am from ${p.place}.`
const firstNames =
["Jon", "Arya", "Jamie"]
const lastNames =
["Snow", "Stark", "Lannister"]
const places =
["The Wall", "Winterfell", "Kings Landing"]
const people =
map(person, firstNames, lastNames, places)
for (const p of people)
console.log(greeting(p))
hello my name is Jon Snow, i am from The Wall.
hello my name is Arya Stark, i am from Winterfell.
hello my name is Jamie Lannister, i am from Kings Landing.