Last active
February 14, 2024 01:54
-
-
Save dotproto/e62d6b8166331d71835d to your computer and use it in GitHub Desktop.
An extension of Array with some additional helper methods I wanted.
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
// 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] |
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
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