Skip to content

Instantly share code, notes, and snippets.

@GoToLoop
Last active November 6, 2020 03:49
Show Gist options
  • Save GoToLoop/a74c5780667f2610097cfc007e53a559 to your computer and use it in GitHub Desktop.
Save GoToLoop/a74c5780667f2610097cfc007e53a559 to your computer and use it in GitHub Desktop.
ArrayList Polyfill Shims for JS Arrays
// ArrayList Polyfill Shims for JS Arrays (v1.0.1)
// GoToLoop (2020/Nov/05)
// https://Gist.GitHub.com/GoToLoop/a74c5780667f2610097cfc007e53a559
"use strict";
// Add some useful Java list's methods to JS arrays as polyfills:
Object.defineProperties(Array.prototype, {
size: {
value() { // polyfill hack to add method size() to JS arrays
return this.length; // return array's current length
}
},
isEmpty: {
value() { // polyfill hack to add method isEmpty() to JS arrays
return !this.length; // return true if length is 0
}
},
clear: {
value() { // polyfill hack to add method clear() to JS arrays
return this.length = 0, this; // remove all elements
}
},
get: {
value(idx) { // polyfill hack to add method get() to JS arrays
return this[idx]; // so its indices can be accessed like a Java list
}
},
set: {
value(idx, elem) { // polyfill hack to add method set() to JS arrays
return this[idx] = elem; // replace elem at specified index
}
},
add: {
value() { // polyfill hack to add method add() to JS arrays
arguments.length > 1?
this.splice(arguments[0], 0, arguments[1]) : // add at specified index
this.push(arguments[0]); // append to array's tail
return this;
}
},
addAll: {
value() { // polyfill hack to add method addAll() to JS arrays
arguments.length > 1?
this.splice(arguments[0], 0, ...arguments[1]) : // add all at index
this.push(...arguments[0]); // append all items to array's tail
return this;
}
},
remove: {
value(val) { // polyfill hack to add method remove() to JS arrays
// idx is val if its type is number, otherwise find its index:
const idx = typeof val == 'number'? val : this.indexOf(val);
// Remove & return the element at index idx or return false:
return ~idx? this.splice(idx, 1)[0] : false;
}
},
toArray: {
value() { // polyfill hack to add method toArray() to JS arrays
if (!arguments.length) return this.slice(); // returns array clone
const [ arr ] = arguments, arrLen = arr.length, thisLen = this.length;
if (arrLen < thisLen) return this.slice(); // returns clone if too small
else if (arrLen > thisLen) arr[thisLen] = null; // marks the array end
for (var i = 0; i < thisLen; arr[i] = this[i++]); // array transfer
return arr; // returns passed array filled w/ this array
}
},
clone: { // method clone() is like invoking slice() w/ no arguments
value: Array.prototype.slice
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment