Skip to content

Instantly share code, notes, and snippets.

@talyssonoc
Last active November 13, 2018 00:41
Show Gist options
  • Save talyssonoc/c31ffcca04853aba12973ba7bc440d38 to your computer and use it in GitHub Desktop.
Save talyssonoc/c31ffcca04853aba12973ba7bc440d38 to your computer and use it in GitHub Desktop.
// User.js
export default class User {
static LEGAL_AGE = 21;
constructor({ id, age }) {
this.id = id;
this.age = age;
}
isMajor() {
return this.age >= User.LEGAL_AGE;
}
}
// usage
import User from './User.js';
const user = new User({ id: 42, age: 21 });
user.isMajor(); // true
// if spread, loses the reference for the class
const user2 = { ...user, age: 20 };
user2.isMajor(); // Error: user2.isMajor is not a function
// User.js
const LEGAL_AGE = 21;
export const isMajor = (user) => {
return user.age >= LEGAL_AGE;
};
// this is a user factory
export const create = (userAttributes) => ({
id: userAttributes.id,
age: userAttributes.age
});
// usage
import * as User from './User.js';
const user = User.create({ id: 42, age: 21 });
User.isMajor(user); // true
// no problem if it's spread
const user2 = { ...user, age: 20 };
User.isMajor(user2); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment