Created
December 17, 2020 02:26
-
-
Save bdombro/6200806535bfaffa75e2d857d5ea28ef to your computer and use it in GitHub Desktop.
ArrayN.js - Extended Array for Rhino
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
'use strict'; | |
var ArrayN = { | |
findIndex: findIndex, | |
find: find, | |
includes: includes, | |
keyBy: keyBy, | |
test: test, | |
}; | |
Object.getOwnPropertyNames(Array).forEach(function(name) { | |
ArrayN[name] = Array[name]; | |
}); | |
module.exports = ArrayN; | |
/** | |
* Like ES6 Array.findIndex | |
* @param {object[]} array | |
* @param {requestCallback} evaluator | |
*/ | |
function findIndex(array, evaluator) { | |
for (let i = 0; i < array.length; i++) { | |
if (evaluator(array[i])) return i; | |
} | |
return -1; | |
} | |
/** | |
* Like ES6 Array.find | |
* @param {object[]} array | |
* @param {requestCallback} evaluator | |
*/ | |
function find(array, evaluator) { | |
const i = findIndex(array, evaluator); | |
return i === -1 ? undefined : array[i]; | |
} | |
/** | |
* Like ES6 Array.includes | |
* @param {object[]} array | |
* @param {object} value | |
*/ | |
function includes(array, value) { | |
const res = array.indexOf(value) !== -1; | |
return res; | |
} | |
/** | |
* Like Lodash Array.keyBy | |
* @param {object[]} array | |
* @param {requestCallback|object} keyOrKeyExtractor | |
*/ | |
function keyBy (array, keyOrKeyExtractor) { | |
const keyExtractor = typeof keyOrKeyExtractor == 'string' | |
? function(obj) { return keyOrKeyExtractor in obj && obj[keyOrKeyExtractor]} | |
: keyOrKeyExtractor | |
const res = {}; | |
array.forEach(function (obj) { | |
const key = keyExtractor(obj); | |
if (key) res[key] = obj; | |
}); | |
return res; | |
} | |
// Add breakpoints to test the result | |
function test() { | |
const arr2 = filter([1,2,3], function(v) {return v === 1}); | |
const arr3 = includes([1,2,3], 2) | |
const o7 = keyBy([{a: 'a1', b: 3}, {a: 'a2', b: 6}], 'a'); | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment