Created
July 27, 2016 08:23
-
-
Save alexandrebodin/a3d843d811bb76d67363e4767bf72214 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const emailSpecification = email => { | |
const expression = 'user.email === email'; | |
return { | |
isSatisfiedBy(user) { | |
return eval(expression); | |
} | |
}; | |
}; | |
const u = { | |
email: '[email protected]', | |
isActive: false, | |
}; | |
const isActiveSpecification = { | |
isSatisfiedBy(user) { | |
return !!user.isActive; | |
} | |
}; | |
const compose = (...specs) => { | |
const specifications = specs.length === 1 ? specs[0] : specs; | |
return { | |
specifications, | |
operator: 'AND', | |
isSatisfiedBy(obj) { | |
for (let i = 0; i < specifications.length ; i++) { | |
if (!specifications[i].isSatisfiedBy(obj)) return false; | |
} | |
return true; | |
} | |
} | |
} | |
const not = (spec) =>({ | |
spec, | |
operatior: 'NOT', | |
isSatisfiedBy(obj) { | |
return !spec.isSatisfiedBy(obj); | |
} | |
}); | |
const and = compose; | |
const or = (...specs) => { | |
const specifications = specs.length === 1 ? specs[0] : specs; | |
return { | |
specifications, | |
operator: 'OR', | |
isSatisfiedBy(obj) { | |
for (let i = 0; i < specifications.length ; i++) { | |
if (specifications[i].isSatisfiedBy(obj)) return true; | |
} | |
return false; | |
} | |
} | |
} | |
const finalSpec = compose( | |
emailSpecification('[email protected]'), | |
not(isActiveSpecification) | |
); | |
const finalSpec2 = compose([emailSpecification('[email protected]'), isActiveSpecification]); | |
const finalSpec3 = or(emailSpecification('alex.a'), isActiveSpecification) | |
const res = emailSpecification('[email protected]').isSatisfiedBy(u); | |
const res1 = finalSpec.isSatisfiedBy(u); | |
const res2 = finalSpec2.isSatisfiedBy(u); | |
const res3 = finalSpec3.isSatisfiedBy(u); | |
console.log(res); | |
console.log(res1); | |
console.log(res2); | |
console.log(res3); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment