Created
January 6, 2020 13:29
-
-
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
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
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