Last active
February 7, 2024 16:13
-
-
Save DarrenSem/bc0403bcdad09912eb298e6d3b4824fe to your computer and use it in GitHub Desktop.
range.js (arraySize, optionalMapFunction, optionalEachFunction)
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
// range(arraySize, optionalMapFunction, optionalEachFunction).js | |
// https://gist.github.com/DarrenSem/bc0403bcdad09912eb298e6d3b4824fe | |
const range = ( arraySize, fnMapIndex, fnEachIndexFirst, _indexes ) => ( | |
_indexes = Array.from( Array(arraySize | 0).keys() ), // because [...Array(arraySize | 0).keys()] triggers TypeScript/VSC error: Type 'IterableIterator' is not an array type or a string type. | |
fnEachIndexFirst && _indexes.forEach( index => fnEachIndexFirst(index) ), | |
fnMapIndex && ( _indexes = _indexes.map( index => fnMapIndex(index) ) ), | |
_indexes | |
); | |
// minified to 91 characters: range = (S,M,E,_)=>(_=Array.from(Array(S|0).keys()),E&&_.forEach(i=>E(i)),M&&(_=_.map(i=>M(i))),_); | |
// basic tests... | |
var counter = 0; | |
console.log([ | |
Array.isArray(range()), | |
Array.isArray(range(null)), | |
Array.isArray(range("foo")), | |
// Array.isArray(range(Infinity)), | |
// range().length === 0, | |
range().length === 0, | |
range(null).length === 0, | |
range("foo").length === 0, | |
// range(Infinity).length === 0, | |
range(3) + "" === "0,1,2", | |
range(3.99) + "" === "0,1,2", | |
range(" 3.99 ") + "" === "0,1,2", | |
// range(-3) => RangeError: Invalid array length | |
Array.isArray(range("-0")), | |
range("-0").length === 0, | |
range(3, Boolean) + "" === "false,true,true", | |
range(4, Array)[3].length === 3, | |
range(4, Array)[3] + "" === ",,", | |
range(4, v => v**2, _ => counter ++) + "" === "0,1,4,9", counter === 4, | |
range(3, v => v*3 + counter, _ => ++ counter) + "" === "7,10,13", counter === 7, | |
range(3, v => v*3 + counter, _ => counter = counter + "-" + _) + "" === "07-0-1-2,37-0-1-2,67-0-1-2" , counter === "7-0-1-2", | |
range(256, String.fromCharCode).toString() === "\x00,\x01,\x02,\x03,\x04,\x05,\x06,\x07,\b,\t,\n,\v,\f,\r,\x0E,\x0F,\x10,\x11,\x12,\x13,\x14,\x15,\x16,\x17,\x18,\x19,\x1A,\x1B,\x1C,\x1D,\x1E,\x1F, ,!,\",#,$,%,&,',(,),*,+,,,-,.,/,0,1,2,3,4,5,6,7,8,9,:,;,<,=,>,?,@,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,[,\\,],^,_,`,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,{,|,},~,\x7F,\x80,\x81,\x82,\x83,\x84,\x85,\x86,\x87,\x88,\x89,\x8A,\x8B,\x8C,\x8D,\x8E,\x8F,\x90,\x91,\x92,\x93,\x94,\x95,\x96,\x97,\x98,\x99,\x9A,\x9B,\x9C,\x9D,\x9E,\x9F,\xa0,¡,¢,£,¤,¥,¦,§,¨,©,ª,«,¬,\xad,®,¯,°,±,²,³,´,µ,¶,·,¸,¹,º,»,¼,½,¾,¿,À,Á,Â,Ã,Ä,Å,Æ,Ç,È,É,Ê,Ë,Ì,Í,Î,Ï,Ð,Ñ,Ò,Ó,Ô,Õ,Ö,×,Ø,Ù,Ú,Û,Ü,Ý,Þ,ß,à,á,â,ã,ä,å,æ,ç,è,é,ê,ë,ì,í,î,ï,ð,ñ,ò,ó,ô,õ,ö,÷,ø,ù,ú,û,ü,ý,þ,ÿ", | |
range(256, String.fromCharCode).join("").trim() === "\x00\x01\x02\x03\x04\x05\x06\x07\b\t\n\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xa0¡¢£¤¥¦§¨©ª«¬\xad®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ", | |
]); | |
var HEX_MAX = 2 ** 8; // 256 AKA 0x100 | |
var BYTE_TO_HEX = range( HEX_MAX, i => (i + HEX_MAX).toString(16).slice(-2) ); | |
console.log( | |
BYTE_TO_HEX + "" === | |
"00,01,02,03,04,05,06,07,08,09,0a,0b,0c,0d,0e,0f,10,11,12,13,14,15,16,17,18,19,1a,1b,1c,1d,1e,1f," | |
+ "20,21,22,23,24,25,26,27,28,29,2a,2b,2c,2d,2e,2f,30,31,32,33,34,35,36,37,38,39,3a,3b,3c,3d,3e,3f," | |
+ "40,41,42,43,44,45,46,47,48,49,4a,4b,4c,4d,4e,4f,50,51,52,53,54,55,56,57,58,59,5a,5b,5c,5d,5e,5f," | |
+ "60,61,62,63,64,65,66,67,68,69,6a,6b,6c,6d,6e,6f,70,71,72,73,74,75,76,77,78,79,7a,7b,7c,7d,7e,7f," | |
+ "80,81,82,83,84,85,86,87,88,89,8a,8b,8c,8d,8e,8f,90,91,92,93,94,95,96,97,98,99,9a,9b,9c,9d,9e,9f," | |
+ "a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,aa,ab,ac,ad,ae,af,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,ba,bb,bc,bd,be,bf," | |
+ "c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,ca,cb,cc,cd,ce,cf,d0,d1,d2,d3,d4,d5,d6,d7,d8,d9,da,db,dc,dd,de,df," | |
+ "e0,e1,e2,e3,e4,e5,e6,e7,e8,e9,ea,eb,ec,ed,ee,ef,f0,f1,f2,f3,f4,f5,f6,f7,f8,f9,fa,fb,fc,fd,fe,ff" | |
); | |
var HEX_TO_BYTE = Object.values(BYTE_TO_HEX).reduce( (acc, value, index) => (acc[value] = index, acc), {} ); | |
var HEX_TO_BYTE_MAP = new Map( Object.entries(BYTE_TO_HEX).map( ([key, value]) => [value, +key] ) ); | |
console.log([ | |
JSON.stringify( HEX_TO_BYTE ) === | |
JSON.stringify( Object.fromEntries( HEX_TO_BYTE_MAP ) ), | |
BYTE_TO_HEX[15] === "0f", | |
HEX_TO_BYTE["0f"] === 15, | |
HEX_TO_BYTE_MAP.get("0f") === 15, | |
BYTE_TO_HEX[HEX_MAX] === undefined, | |
HEX_TO_BYTE["fg"] === undefined, | |
HEX_TO_BYTE_MAP.get("fg") === undefined, | |
]); | |
/* | |
This `range` JS function is designed to create a range of numbers, optionally process each number, and optionally transform each number with different functions. | |
Let's break down what it does step by step: | |
1. **Create an array of numbers**: `(size = [...Array(size).keys()])` | |
- Here, a new array with the length of `size` is created using `Array(size)`. | |
- Then, `.keys()` is called on this array, which returns an iterator for the keys (which in the case of an array, are just the indices). | |
- Finally, `[...iterator]` is a spread syntax that converts the iterator into an actual array of numbers, starting from 0 up to `size - 1`. | |
2. **Optionally call a function on each number**: `(fnEach && size.forEach(el => fnEach(el)))` | |
- This line checks if a function `fnEach` was provided. | |
- If it was, the `.forEach()` method is used to call the `fnEach` function on every element of the array. | |
3. **Optionally transform each number**: `(fnMap && (size = size.map(el => fnMap(el))))` | |
- Similar to the previous step, this line checks if a function `fnMap` was provided. | |
- If it was, the `.map()` method is used on the array, applying the `fnMap` function to every element, thus creating a new array with the transformed values. | |
4. **Return the updated array**: `size` | |
- After all the optional processing, the final array is returned. | |
Why would someone want to use this function? Here are a few potential reasons: | |
- To generate a list of numbers within a certain range. | |
- To perform an action on each number in that range without writing a loop manually. | |
- To modify each number in the range easily, perhaps to generate a sequence of numbers based on a particular formula. | |
- To avoid writing extra code to create and process the range, thus making the developer's code more compact and readable. | |
This kind of function could be used in various scenarios, like generating options for a numerical dropdown, creating pagination links, or any other situation where you'd need a sequence of numbers that may also need to be processed or transformed in some way. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment