Computed properties for regular JavaScript objects.
This project is heavily inspired by Ember.
You may have to include es5-shim and es6-shim depending on the browser you're targeting.
- NPM:
npm install fnando/computed
(latest) ornpm install fnando/computed#v0.2.0
(specific version) - Bower:
bower install fnando/computed
(latest) ornpm install fnando/computed#v0.2.0
(specific version)
Importing module:
- Node.js:
const Computed = require('computed');
- AMD:
define(['computed'], function(Computed) {});
- Browser:
Computed
A computed property that performs a logical and
on the original values.
All values use JavaScript's truthy/falsy checking, with
exception of numbers (even zero is considered truthy).
var hamster = {
readyForCamp: Computed.and('hasTent', 'hasBackpack')
};
hamster.readyForCamp(); // false
hamster.hasTent = true;
hamster.readyForCamp(); // false
hamster.hasBackpack = true;
hamster.readyForCamp(); // true
Creates a new property that is an alias for another property on an object.
var post = {
id: 'some-post',
slug: Computed.alias('id')
};
post.slug(); // some-post
post.slug('a-new-post');
post.id; // a-new-post
A computed property that returns the first truthy value from a list of dependent properties.
var hamster = {
hasClothes: Computed.any('hat', 'shirt')
};
hamster.hasClothes(); // null
hamster.shirt = 'Hawaiian Shirt';
hamster.hasClothes(); // 'Hawaiian Shirt'
A computed property that returns an object containing all listed
properties. Aliased as Computed.attrs
.
var hamster = {
name: 'John',
age: 42,
salary: 1000,
attributes: Computed.attributes('name', 'age')
};
hamster.attributes(); // {name: 'John', age: 42}
A computed property that converts the provided dependent property into a boolean value.
var hamster = {
hasBananas: Computed.bool('numBananas')
};
hamster.hasBananas(); // false
hamster.numBananas = 0;
hamster.hasBananas(); // false
hamster.numBananas = 1;
hamster.hasBananas(); // true
hamster.numBananas = null;
hamster.hasBananas(); // false
A computed property that returns the array of values for the provided dependent properties.
var hamster = {
clothes: Computed.collect('hat', 'shirt')
};
hamster.clothes(); // [undefined, undefined]
hamster.hat = 'Camp Hat';
hamster.shirt = 'Camp Shirt';
hamster.clothes(); // ['Camp Hat', 'Camp Shirt']
A computed property that returns true if the value of the dependent property is null/undefined, an empty string, or empty array.
var todoList = {
todos: ['Unit Test', 'Documentation', 'Release'],
done: Computed.empty('todos')
};
todoList.done(); // false
todoList.todos.length = 0;
todoList.done(); // true
A computed property that returns true if the provided dependent property is equal to the given value.
var hamster = {
napTime: Computed.equal('state', 'sleepy')
};
hamster.napTime(); // false
hamster.state = 'sleepy';
hamster.napTime(); // true
hamster.state = 'hungry';
hamster.napTime(); // false
Filters the array by the callback.
The callback method you provide should have the following signature: function(item, index){}
.
-
item
is the current item in the iteration. -
index
is the integer index of the current item in the iteration.
var hamster = {
chores: [
{name: 'cook', done: true},
{name: 'clean', done: true},
{name: 'write more unit tests', done: false}
],
remainingChores: Computed.filter('chores', function(chore, index) {
return !chore.done;
})
};
hamster.remainingChores(); // [{name: 'write more unit tests', done: false}]
Filters the array by the property and value.
var hamster = {
chores: [
{name: 'cook', done: true},
{name: 'clean', done: true},
{name: 'write more unit tests', done: false}
],
remainingChores: Computed.filterBy('chores', 'done', false)
};
hamster.remainingChores(); // [{name: 'write more unit tests', done: false}]
A computed property that returns true if the provided dependent property is greater than the provided value.
var hamster = {
hasTooManyBananas: Computed.gt('numBananas', 10)
};
hamster.hasTooManyBananas(); // false
hamster.numBananas = 3;
hamster.hasTooManyBananas(); // false
hamster.numBananas = 11;
hamster.hasTooManyBananas(); // true
A computed property that returns true if the provided dependent property is greater than or equal to the provided value.
var hamster = {
hasTooManyBananas: Computed.gte('numBananas', 10)
};
hamster.hasTooManyBananas(); // false
hamster.numBananas = 3;
hamster.hasTooManyBananas(); // false
hamster.numBananas = 10;
hamster.hasTooManyBananas(); // true
A computed property that returns true if the provided dependent property is less than the provided value.
var hamster = {
needsMoreBananas: Computed.lt('numBananas', 3)
};
hamster.needsMoreBananas(); // true
hamster.numBananas = 3;
hamster.needsMoreBananas(); // false
hamster.numBananas = 2;
hamster.needsMoreBananas(); // true
A computed property that returns true if the provided dependent property is less than or equal to the provided value.
var hamster = {
needsMoreBananas: Computed.lte('numBananas', 3)
};
hamster.needsMoreBananas(); // true
hamster.numBananas = 5;
hamster.needsMoreBananas(); // false
hamster.numBananas = 3;
hamster.needsMoreBananas(); // true
Returns an array mapped via the callback
The callback method you provide should have the following signature: function(item, index){}
- item is the current item in the iteration.
- index is the integer index of the current item in the iteration.
var hamster = {
chores: ['clean', 'write more unit tests'],
excitingChores: Computed.map('chores', function(chore, index) {
return chore.toUpperCase() + '!';
})
};
hamster.excitingChores(); // ['CLEAN!', 'WRITE MORE UNIT TESTS!']
Maps the array by the property and value.
var info = {
countries: [{id: 1, name: 'Brazil'}, {id: 2, name: 'USA'}],
names: Computed.mapBy('countries', 'name')
};
object.names(); // ['Brazil', 'USA']
A computed property which matches the original value for the dependent property against a given RegExp, returning true if they values matches the RegExp and false if it does not.
var user = {
hasValidEmail: Computed.match('email', /^.+@.+\..+$/)
};
user.hasValidEmail(); // false
user.email = '';
user.hasValidEmail(); // false
user.email = 'john@example.com';
user.hasValidEmail(); // true
A computed property that calculates the maximum value in the dependent
array. This will return -Infinity
when the dependent array is empty.
var object = {
numbers: [1,2,3,4,5],
maxNumber: Computed.max('numbers')
};
object.maxNumber(); // 5
A computed property that calculates the minimum value in the dependent
array. This will return Infinity
when the dependent array is empty.
var object = {
numbers: [1,2,3,4,5],
minNumber: Computed.min('numbers')
};
object.minNumber(); // 1
A computed property that returns true if the value of the dependent
property is null
or undefined
.
var hamster = {
isHungry: Computed.none('food')
};
hamster.isHungry(); // true
hamster.food = 'Banana';
hamster.isHungry(); // false
hamster.food = null;
hamster.isHungry(); // true
A computed property that returns the inverse boolean value of the original value for the dependent property.
var user = Ember.Object.extend({
loggedIn: false,
isAnonymous: Computed.not('loggedIn')
});
user.isAnonymous(); // true
user.loggedIn = true;
user.isAnonymous(); // false
A computed property that returns true if the value of the dependent property is NOT null, an empty string, or empty array.
var hamster = {
backpack: ['Food', 'Sleeping Bag', 'Tent'],
hasStuff: Computed.notEmpty('backpack')
};
hamster.hasStuff(); // true
hamster.backpack.length = 0; // []
hamster.hasStuff(); // false
A computed property which performs a logical or on the original values for the provided dependent properties.
var hamster = {
readyForRain: Computed.or('hasJacket', 'hasUmbrella')
});
hamster.readyForRain(); // false
hamster.hasJacket = true;
hamster.readyForRain(); // true
A computed property which returns a new array with all the properties from the first dependent array sorted based on a property or sort function.
The callback method you provide should have the following signature: function(itemA, itemB)
.
- itemA the first item to compare.
- itemB the second item to compare.
This function should return negative number (e.g. -1) when itemA should come before itemB. It should return positive number (e.g. 1) when itemA should come after itemB. If the itemA and itemB are equal this function should return 0.
Therefore, if this function is comparing some numeric values, simple itemA - itemB can be used instead of series of if.
var info = {
names: ['John', 'Bob', 'Mary'],
sortedNames: Computed.sort('names', function(a, b){
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
return 1;
})
};
info.sortedNames(); // ['Bob', 'John', 'Mary']
Sorts the array by the property and value.
var info = {
users: [{name: 'John'}, {name: 'Bob'}, {name: 'Mary'}],
sortedNames: Computed.sortBy('users', 'name')
};
info.sortedNames(); // ['Bob', 'John', 'Mary']
A computed property which returns a new array with all the unique elements from one or more dependent arrays.
var hamster = {
fruits: ['banana', 'grape', 'kale', 'banana'],
uniqueFruits: Computed.uniq('fruits')
};
hamster.uniqueFruits(); // ['banana', 'grape', 'kale']
To set a property:
var user = {profile: {}};
Computed.set(user, 'name', 'John Doe');
Computed.set(user, 'profile.twitter', 'johndoe');
To read a property, even when it's computed:
Computed.get(user, 'name');
Computed.get(user, 'profile.twitter');
The next section covers how you can use Computed in constructor functions.
Computed can be used to define prototype properties.
// Set a base constructor function, so we don't need
// to do this every time.
function Base() {}
Base.prototype = {
get: Computed.get,
set: Computed.set
};
// Define the User constructor function.
function User() {}
User.prototype = Object.create(Base.prototype);
User.prototype.hasConfirmedAccount = Computed.bool('accountConfirmedAt');
// Instantiate a new user.
var user = new User();
user.get('hasConfirmedAccount'); // false
user.set('accountConfirmedAt', new Date());
user.get('hasConfirmedAccount'); // true
- Nando Vieira - http://nandovieira.com.br
Once you've made your great commits:
- Fork Computed.js
- Create a topic branch -
git checkout -b my_branch
- Push to your branch -
git push origin my_branch
- Create an Issue with a link to your branch
- That's it!
Please respect the indentation rules and code style. And use 2 spaces, not tabs. And don't touch the versioning thing.
Make sure you have Phantom.js installed.
$ npm install
$ bower install
$ npm run watch
$ npm test
(The MIT License)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.