flags.ts 1.0 KB

123456789101112131415161718192021222324252627
  1. type FlagHandler = (flag: number) => (flags: number) => number | boolean
  2. const applyFlagHandler = (fn: FlagHandler) => (flags: number) => (initial = 0) => fn(flags)(initial)
  3. const $isset = (flag: number) => (flags = 0): boolean => (flags & flag) === flag
  4. const $set = (flag: number) => (flags = 0): number => flags | flag
  5. const $unset = (flag: number) => (flags = 0): number => flags ^ flag
  6. const $toggle = (flag: number) => (flags = 0): number => $isset(flag)(flags) ? $unset(flag)(flags) : $set(flag)(flags)
  7. const combine = (...options: number[]) => options.reduce((flags, flag) => $set(flag)(flags), 0)
  8. const createMultiFlagHandler = (fn: FlagHandler) => (...options: number[]) => (flags = 0) => applyFlagHandler(fn)(combine(...options))(flags)
  9. const set = createMultiFlagHandler($set)
  10. const unset = createMultiFlagHandler($unset)
  11. const toggle = createMultiFlagHandler($toggle)
  12. const isset = createMultiFlagHandler($isset)
  13. const settings = set(1, 4, 8)()
  14. console.log(isset(4)(settings))
  15. export {
  16. combine,
  17. set,
  18. unset,
  19. toggle,
  20. isset
  21. }