angus-c / just

A library of dependency-free JavaScript utilities that do just one thing.
https://anguscroll.com/just
MIT License
6.07k stars 209 forks source link

Proposal: `hasOnly` object utility #558

Open arimgibson opened 1 year ago

arimgibson commented 1 year ago

Long time user of just, first time contributor!

I wanted to add a suggestion for a new object utility called hasOnly, which checks whether a specified object has only certain keys.

My ideal implementation is not ES5 compatible as it relies on Array.includes(). I've found some polyfills online but might need help from maintainers/anyone more ES5 familiar to ensure it works as expected still and covers all edge cases.

Have read the contribution guidelines and am willing to submit the necessary code, tests, and PR, but wanted to run it by maintainers before going through the work. Thanks!

import hasOnly from 'just-has-only'

hasOnly({ email: 'example@example.com', password: 'pass123' }, ['email']) // false
hasOnly({ email: 'example@example.com', password: 'pass123' }, ['email', 'password']) // true 

var obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  e: 5
};

hasOnly(obj, ['b', 'c']) // false
hasOnly(obj, ['a', 'b', 'c', 'd']) // false
hasOnly(obj, ['a', 'b', 'c', 'd', 'e']) // true
function hasOnly(object: Record<string, any>, keys: string[]) {
  return Object.keys(object).every((key) => keys.includes(key));
}

export {hasOnly as default};