@toreda/strong-types
Version:
Better TypeScript code in fewer lines.
1 lines • 1.2 kB
Source Map (JSON)
{"version":3,"sources":["../src/swap/pop.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,wBAAgB,OAAO,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI,CAgC5D","file":"pop.d.ts","sourcesContent":["/**\n * Remove an array element in O(1) time if element ndx is known.\n * Works only with unordered arrays.\n * @param array\n * @param ndx\n *\n * @category Collections\n */\nexport function swapPop<T>(array: T[], ndx: number): T | null {\n\tif (!array.length) {\n\t\t// pop always returns a value if the length is greater\n\t\t// than zero. This check prevents pop from returning a\n\t\t// value of undefined.\n\t\treturn null;\n\t}\n\n\tif (ndx >= array.length || ndx < 0) {\n\t\treturn null;\n\t}\n\n\tif (array.length === 1 || ndx === array.length - 1) {\n\t\tconst result = array.pop();\n\t\tif (result === undefined) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t// Save the element at ndx in the array to\n\t// keep it safe while we overwrite the slot.\n\tconst element = array[ndx];\n\n\t// Move the last element into ndx slot.\n\tarray[ndx] = array[array.length - 1];\n\n\t// Pop the last element off the array\n\tarray.pop();\n\n\treturn element;\n}\n"]}