Skip to content

Instantly share code, notes, and snippets.

@dotproto
Last active February 14, 2024 01:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotproto/e62d6b8166331d71835d to your computer and use it in GitHub Desktop.
Save dotproto/e62d6b8166331d71835d to your computer and use it in GitHub Desktop.
An extension of Array with some additional helper methods I wanted.
// Example usage
var List = require('List');
// Instantiate instances using `new`
var list = new List();
// Use .add to append a one or more unique items to the list
list.add('foo');
list.add('BAR', 'BAZ');
list.add(1, 2,2, 3,3,3, 4,4,4,4);
console.log(list); // ["foo", "BAR", "BAZ", 1, 2, 3, 4]
// Similarly, you can use .remove to drop or or more items from the list
list.remove('foo');
list.remove(2,4);
console.log(list); // ["bar", "BAR", "BAZ", 1, 3, 4]
function List () {}
List.prototype = []
List.prototype.constructor = List
List.prototype._return = function _return (val) {
if (val.length <= 1)
val = val[0]
return val
}
List.prototype.add = function add () {
var results = []
for (var i = 0, len = arguments.length; i < len; i++) {
if (this.indexOf(arguments[i]) === -1)
results.push(this.push(arguments[i]))
}
if (results.length)
return this._return(results)
else
return this.length
}
List.prototype.remove = function remove (item) {
var results = [],
idx = this.indexOf(item)
if (idx !== -1)
return this.splice(idx, 1)
for (var i = 0, len = arguments.length; i < len; i++) {
idx = this.indexOf(arguments[i])
if (idx === -1)
results.push(this.splice(idx, 1))
}
return this._return(results)
}
module.exports = List
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment