Last active
July 5, 2023 09:29
-
-
Save JoeNoPhoto/329f002ef4f92f1fcc21280dc2f4aa71 to your computer and use it in GitHub Desktop.
(ES6) Avoiding Array Mutations with concat(), slice(), and ...spread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const addCounter = (list) => { | |
return [...list, 0]; | |
}; | |
const removeCounter = (list, index) => {\ | |
return [ | |
...list.slice(0, index), | |
...list.slice(index + 1) | |
]; | |
}; | |
const incrementCounter = (list, index) => { | |
return [ | |
...list.slice(0, index), | |
list[index] + 1, | |
...list.slice(index + 1) | |
]; | |
}; | |
const testAddCounter = () => { | |
const listBefore = []; | |
const listAfter = [0]; | |
deepFreeze(listBefore); | |
expect( | |
addCounter(listBefore) | |
).toEqual(listAfter); | |
} | |
const testRemoveCounter = () => { | |
const listBefore = [0, 10, 20]; | |
const listAfter = [0, 20]; | |
deepFreeze(listBefore); | |
expect( | |
removeCounter(listBefore, 1) | |
).toEqual(listAfter); | |
}; | |
const testIncrementCounter = () => { | |
const listBefore = [0, 10, 20]; | |
const listAfter = [0, 11, 20]; | |
deepFreeze(listBefore); | |
expect( | |
removeCounter(listBefore, 1) | |
).toEqual(listAfter); | |
}; | |
} | |
testAddCounter(); | |
testRemoveCounter(); | |
testIncrementCounter(); | |
console.log('all tests passed'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
expect for testing: | |
<script src="https://wzrd.in/standalone/expect@latest"></script> | |
deepFreeze for not allowing mutations: | |
<script src="https://wzrd.in/standalone/deep-freeze@latest"></script> | |
--> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
<script src="https://wzrd.in/standalone/expect@latest"></script> | |
<script src="https://wzrd.in/standalone/deep-freeze@latest"></script> | |
</head> | |
<body> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment