Skip to content

Commit 636017c

Browse files
authored
algorithm: reverse (TheAlgorithms#1197)
1 parent b07529f commit 636017c

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

Data-Structures/Array/Reverse.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/** https://www.geeksforgeeks.org/write-a-program-to-Reverse-an-array-or-string/
2+
* This function will accept an array and
3+
* Reverse its elements and returns the inverted array
4+
* @param {Array} arr array with elements of any data type
5+
* @returns {Array} array with inverted elements
6+
*/
7+
8+
const Reverse = (arr) => {
9+
// limit specifies the amount of Reverse actions
10+
for (let i = 0, j = arr.length - 1; i < arr.length / 2; i++, j--) {
11+
const temp = arr[i]
12+
arr[i] = arr[j]
13+
arr[j] = temp
14+
}
15+
return arr
16+
}
17+
export { Reverse }
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { Reverse } from '../Reverse.js'
2+
import each from 'jest-each'
3+
4+
describe('reverse elements in an array', () => {
5+
each`
6+
array | expected
7+
${[]} | ${[]}
8+
${[1]} | ${[1]}
9+
${[1, 2, 3, 4]} | ${[4, 3, 2, 1]}
10+
`.test('returns $expected when given $array', ({ array, expected }) => {
11+
expect(Reverse(array)).toEqual(expected)
12+
})
13+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy