mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
algorithm: reverse (#1197)
This commit is contained in:
17
Data-Structures/Array/Reverse.js
Normal file
17
Data-Structures/Array/Reverse.js
Normal file
@ -0,0 +1,17 @@
|
||||
/** https://www.geeksforgeeks.org/write-a-program-to-Reverse-an-array-or-string/
|
||||
* This function will accept an array and
|
||||
* Reverse its elements and returns the inverted array
|
||||
* @param {Array} arr array with elements of any data type
|
||||
* @returns {Array} array with inverted elements
|
||||
*/
|
||||
|
||||
const Reverse = (arr) => {
|
||||
// limit specifies the amount of Reverse actions
|
||||
for (let i = 0, j = arr.length - 1; i < arr.length / 2; i++, j--) {
|
||||
const temp = arr[i]
|
||||
arr[i] = arr[j]
|
||||
arr[j] = temp
|
||||
}
|
||||
return arr
|
||||
}
|
||||
export { Reverse }
|
13
Data-Structures/Array/test/Reverse.test.js
Normal file
13
Data-Structures/Array/test/Reverse.test.js
Normal file
@ -0,0 +1,13 @@
|
||||
import { Reverse } from '../Reverse.js'
|
||||
import each from 'jest-each'
|
||||
|
||||
describe('reverse elements in an array', () => {
|
||||
each`
|
||||
array | expected
|
||||
${[]} | ${[]}
|
||||
${[1]} | ${[1]}
|
||||
${[1, 2, 3, 4]} | ${[4, 3, 2, 1]}
|
||||
`.test('returns $expected when given $array', ({ array, expected }) => {
|
||||
expect(Reverse(array)).toEqual(expected)
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user