const listOfNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
const listOfEvenNumbers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
const listOfNumbersWithOneOdd = [2, 4, 6, 8, 10, 12, 14, 3, 16, 18, 20]
// Map ---------------------------------
const _map = (array) => {
const newArray = []
array.forEach((number) => {
newArray.push(number * 2)
})
return newArray
}
console.log(_map(listOfNumbers))
// Filter ---------------------------------
const _filter = (array) => {
const newArray = []
array.forEach((number, index) => {
if (number % 2 === 0) {
newArray.push(number)
}
})
return newArray
}
console.log(_filter(listOfNumbers))
// Reduce ---------------------------------
const _reduce = (array) => {
let total = 0
array.forEach((number) => {
total = total + number
})
return total
}
console.log(_reduce(listOfNumbers))
// Every ---------------------------------
const _every = (array) => {
let allNumbersAreEven = true
array.forEach((number) => {
if (number % 2 === 1) {
allNumbersAreEven = false
}
})
return allNumbersAreEven
}
console.log(_every(listOfEvenNumbers))
console.log(_every(listOfNumbersWithOneOdd))
// Some ---------------------------------
const _some = (array) => {
let atleastOneOdd = false
array.forEach((number) => {
if (number % 2 === 1) {
atleastOneOdd = true
}
})
return atleastOneOdd
}
console.log(_some(listOfEvenNumbers))
console.log(_some(listOfNumbersWithOneOdd))
After completing this assignment, you should be able to:
- Demonstrate understanding of iteration/enumeration
- Fork this repository to your own account.
- Change into your projects directory:
- Clone your repository:
hub clone js-iteration
- Change into your project's directory:
cd js-iteration
- Install the dependencies:
yarn install
(or justyarn
for short) - Open in your editor]
- Start the test runner:
yarn test
- Open
src/functions.test.js
and work on functions until tests pass. - Commit and push your work to GitHub.
- Turn in the URL to your GitHub repo.
- Using the
forEach
looping method and no other looping or enumeration helper, write your own version of the following methods, except name yours_map
,_filter
, etc.map
filter
reduce
every
some
- Write some example usage of your new methods to demonstrate that they work
Reference the documentation on DevDocs to find what kind of helpful functions might already be in JavaScript.