Skip to content

Instantly share code, notes, and snippets.

@fisknils
Created April 23, 2019 08:25
Show Gist options
  • Save fisknils/a533a37bf729a3e59f97f7085e627310 to your computer and use it in GitHub Desktop.
Save fisknils/a533a37bf729a3e59f97f7085e627310 to your computer and use it in GitHub Desktop.
Javascript Collection class
'use strict';
class Collection extends Array {
query(pattern){
var regex = new RegExp(pattern);
return this.filter(function(entry){
return regex.test(entry);
});
}
unique() {
return this.filter((value, index, self) => self.indexOf(value) === index);
}
onlyUnique() {
var that = this;
return that.filter(function(entry){
return that.filter(function(entry1){
return (entry === entry1);
}).length === 1
});
}
}
/**
Examples:
> var mycollection = new Collection('hello','hello world', 'hello');
> mycollection.query('hello');
>> Collection(3) ["hello", "hello world", "hello"]
> mycollection.query(' ');
>> Collection ["hello world"]
> mycollection.query('^hello$');
>> Collection(2) ["hello", "hello"]
> mycollection.query('^hello$').unique();
>> Collection ["hello"]
> mycollection.unique();
>> Collection(2) ["hello", "hello world"]
> mycollection.onlyUnique();
>> Collection ["hello world"]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment