Last active
May 12, 2022 21:35
-
-
Save rauschma/5515bea8e30f68188daf721df5da65eb to your computer and use it in GitHub Desktop.
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
import * as assert from 'assert/strict'; | |
/** | |
* I’m not sure if this is practically useful but: | |
* The single utility method .findValue() for Arrays can be used | |
* to implement several existing Array methods. | |
*/ | |
Array.prototype.findValue = function (cb, defaultResult, thisValue) { | |
thisValue ??= this; | |
for (let i=0; i<this.length; i++) { | |
const result = cb .call(thisValue, this[i], i, this); | |
if (result !== null && typeof result === 'object' && 'value' in result) { | |
return result.value; | |
} | |
} | |
return defaultResult; | |
}; | |
////////// .find((x) => x > 0) ////////// | |
assert.equal( | |
[-1, 0, -7, 123].findValue((x) => x > 0 ? {value: x} : undefined, undefined), | |
123 | |
); | |
assert.equal( | |
[-1, 0, -7].findValue((x) => x > 0 ? {value: x} : undefined, undefined), | |
undefined | |
); | |
////////// .findIndex((x) => x > 0) ////////// | |
assert.equal( | |
[-1, 0, -7, 123].findValue((x, index) => x > 0 ? {value: index} : undefined, -1), | |
3 | |
); | |
assert.equal( | |
[-1, 0, -7].findValue((x, index) => x > 0 ? {value: index} : undefined, -1), | |
-1 | |
); | |
////////// Return both value and index at the same time ////////// | |
assert.deepEqual( | |
[-1, 0, -7, 123].findValue((x, index) => x > 0 ? {value: {index, value:x}} : undefined, undefined), | |
{ index: 3, value: 123 } | |
); | |
assert.equal( | |
[-1, 0, -7].findValue((x, index) => x > 0 ? {value: {index, value:x}} : undefined, undefined), | |
undefined | |
); | |
////////// .some((x) => x.length > 0) ////////// | |
assert.equal( | |
['', 'a', ''].findValue((x) => x.length > 0 ? {value:true} : undefined, false), | |
true | |
); | |
assert.equal( | |
['', '', ''].findValue((x) => x.length > 0 ? {value:true} : undefined, false), | |
false | |
); | |
////////// .every((x) => x.length > 0) ////////// | |
assert.equal( | |
['', 'a', ''].findValue((x) => x.length === 0 ? {value:false} : undefined, true), | |
false | |
); | |
assert.equal( | |
['a', 'b', 'c'].findValue((x) => x.length === 0 ? {value:false} : undefined, true), | |
true | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment