Skip to content

Instantly share code, notes, and snippets.

@armanozak
Created January 6, 2020 13:29
Show Gist options
  • Save armanozak/9255e308e716166c4c1abba5041eb64e to your computer and use it in GitHub Desktop.
Save armanozak/9255e308e716166c4c1abba5041eb64e to your computer and use it in GitHub Desktop.
[Strategy Pattern & Higher Order Functions] How to Switch Algorithms at Run-Time #javascript #tips
function createDeepTruthChecker(useStrategy = Object.keys) {
return function check(obj) {
return !!obj && (
typeof obj === 'object'
? useStrategy(obj).every(key => check(obj[key]))
: true
);
};
}
function NoEmptyStrategy(obj) {
const keys = Object.keys(obj);
return keys.length ? keys : keys.concat('length');
}
const checkDeepTruth = createDeepTruthChecker();
const checkDeepTruthNoEmpty = createDeepTruthChecker(NoEmptyStrategy);
checkDeepTruth({ demo: [] }); // true
checkDeepTruthNoEmpty({ demo: [] }); // false
checkDeepTruthNoEmpty({ demo: [ 'test' ]}); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment