Created
January 14, 2020 05:30
-
-
Save nicoandmee/5cafdf7924cd000f1409f4f71d47ca7c to your computer and use it in GitHub Desktop.
[Range Functions in Javascript]
This file contains hidden or 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
| // Numbers | |
| [...Array(5).keys()]; | |
| => [0, 1, 2, 3, 4] | |
| // Character iteration | |
| String.fromCharCode(...[...Array('D'.charCodeAt(0) - 'A'.charCodeAt(0) + 1).keys()].map(i => i + 'A'.charCodeAt(0))); | |
| => "ABCD" | |
| // muh iteratos | |
| for (const x of Array(5).keys()) { | |
| console.log(x, String.fromCharCode('A'.charCodeAt(0) + x)); | |
| } | |
| => 0,"A" 1,"B" 2,"C" 3,"D" 4,"E" | |
| // Functions | |
| function range(size, startAt = 0) { | |
| return [...Array(size).keys()].map(i => i + startAt); | |
| } | |
| function characterRange(startChar, endChar) { | |
| return String.fromCharCode(...range(endChar.charCodeAt(0) - | |
| startChar.charCodeAt(0), startChar.charCodeAt(0))) | |
| } | |
| // Typed | |
| function range(size:number, startAt:number = 0):ReadonlyArray<number> { | |
| return [...Array(size).keys()].map(i => i + startAt); | |
| } | |
| function characterRange(startChar:string, endChar:string):ReadonlyArray<string> { | |
| return String.fromCharCode(...range(endChar.charCodeAt(0) - | |
| startChar.charCodeAt(0), startChar.charCodeAt(0))) | |
| } | |
| // Lodash copout | |
| _.range(10); | |
| => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
| _.range(1, 11); | |
| => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
| _.range(0, 30, 5); | |
| => [0, 5, 10, 15, 20, 25] | |
| _.range(0, -10, -1); | |
| => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] | |
| String.fromCharCode(..._.range('A'.charCodeAt(0), 'D'.charCodeAt(0) + 1)); | |
| => "ABCD" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment