Skip to content

Instantly share code, notes, and snippets.

@ironstrider
ironstrider / shuffle.js
Last active March 17, 2022 22:52
Implementation of Fisher-Yates in Javascript to shuffle an array
function fisherYates(array) {
let i = array.length;
let temp, j;
while(i) {
j = (Math.random() * i--) | 0; // x | 0 gives floor(x)
// swap elements i & j
temp = array[i];
array[i] = array[j];
@ironstrider
ironstrider / findLastIndex.js
Last active March 5, 2022 22:28
Search javascript array from the *right* to find the (index of the) *last* element satisfying a condition
// Returns the index of the last array element that satisfies a condition function. Otherwise, returns -1
// Similar to Array.prototype.findIndex, but finds the *last* element by searching from the right
// Parameters are exactly the same as findIndex:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
function findLastIndex(array, callbackFn, thisArg) {
for (let i = array.length - 1; i >= 0; i--) {
if(callbackFn.call(thisArg, array[i], i, array)) {
return i
}