Skip to content

Commit 3292e5b

Browse files
First commit
0 parents  commit 3292e5b

File tree

4 files changed

+82
-0
lines changed

4 files changed

+82
-0
lines changed

README.md

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
## Recursive javascript
2+
3+
Common functions implemented using recursion
4+
5+
---
6+
7+
### Implemented:
8+
9+
- map
10+
- filter
11+
- flatten
12+
13+
### Suggestions?
14+
15+
Please create an issue!

filter.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
*
3+
* @param {Array} arr array of elements
4+
* @param {Function} fn function that checks if the element satisfy the condition
5+
* @returns {Array} a new array with the elements that satisfy the condition
6+
*/
7+
function filter(arr, condition) {
8+
if (arr.length === 0) return []
9+
const x = arr[0]
10+
const xs = arr.slice(1)
11+
return (condition(x) ? [x] : []).concat(filter(xs, condition))
12+
}
13+
14+
15+
const greaterThanTwo = (e) => e > 2
16+
17+
console.log(filter([1,2,3], greaterThanTwo))
18+
console.log(filter([2], greaterThanTwo))
19+
console.log(filter([], greaterThanTwo))
20+
console.log(filter([-1, 2, 44], greaterThanTwo))
21+
22+
const isTrue = (e) => e
23+
console.log(filter([true, true, false], isTrue))

flatten.js

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
*
3+
* @param {Array} arr array multi level
4+
* @returns {Array} a new array with the elements in the same level
5+
*/
6+
function flatten(arr) {
7+
if (arr.length === 0) return []
8+
const x = arr[0]
9+
const xs = arr.slice(1)
10+
if (arr.length === 1) return Array.isArray(x) ? flatten(x) : [x]
11+
return flatten([x]).concat(flatten(xs))
12+
}
13+
14+
console.log(flatten([]))
15+
console.log(flatten([1]))
16+
console.log(flatten([1,2]))
17+
console.log(flatten([1,2,3]))
18+
console.log(flatten([1,2, [3, 4, [[[5], 6], 7]]]))

map.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
*
3+
* @param {Array} arr array of elements
4+
* @param {Function} fn function to be applied to each element
5+
* @returns {Array} a new array with the function applied to each elements
6+
*/
7+
function map(arr, fn) {
8+
if (arr.length === 0) return []
9+
const x = arr[0]
10+
const xs = arr.slice(1)
11+
return [fn(x)].concat(map(xs, fn))
12+
}
13+
14+
15+
const plusOne = (e) => e + 1
16+
console.log(map([1,2,3], plusOne))
17+
console.log(map([2], plusOne))
18+
console.log(map([], plusOne))
19+
20+
const getName = (e) => e.name
21+
const objs = [
22+
{name: 'Ale', age: 27},
23+
{name: 'Juan', age: 27},
24+
{name: 'Maria', age: 27},
25+
]
26+
console.log(map(objs, getName))

0 commit comments

Comments
 (0)