JSFiddle - React, Tailwind, and code Playground
by Lyndsy Simon
JavaScript
var foo = {'name': 'foo'};
var bar = {'name': 'bar'};
// utility method
var ensure_tags_attribute = function(obj) {
if (obj.tags === undefined) {
obj.tags = [];
}
}
// add a tag to any object
var add_tag = function(tag) {
ensure_tags_attribute(this);
if (this.tags.indexOf(tag) == -1) {
this.tags.push(tag);
}
};
// print any object's tags to console
var log_tags = function () {
ensure_tags_attribute(this);
console.log(this.tags.length + ' tags for this object')
if (this.tags.length > 0) {
console.log(this.tags.map(function(x) { return '- ' + x; }).join('\n'));
}
}
// Add a tag to foo
add_tag.call(foo, '#call');
// Create a function - i.e., a bound method - that adds a tag to foo.
var add_tag_to_foo = add_tag.bind(foo);
add_tag_to_foo('#bind')
// Create a function that adds the tag "alpha" to foo
var add_alpha_to_foo = add_tag.bind(foo, "#bind (curried)");
add_alpha_to_foo();
// Get tags for the foo
console.log('== foo ==');
log_tags.apply(foo);
// There are no tags for bar
console.log('== bar ==');
log_tags.apply(bar);
// It works for arbitrary objects!
console.log('== document.body ==');
log_tags.apply(document.body);
console.log('... add a tag ...');
add_tag.call(document.body, 'alpha');
log_tags.apply(document.body);