All files / nothis/utils getAllKeys.js

100% Statements 18/18
100% Branches 8/8
100% Functions 4/4
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 473x       3x                             99x 99x       11x 11x 11x 15x 231x 99x 86x       15x   11x     3x 11x 11x 11x     3x  
const uniq = require('./uniq')
 
// from: http://code.fitness/post/2016/01/javascript-enumerate-methods.html
 
const excluded = [
  'constructor',
  '__defineGetter__',
  '__defineSetter__',
  '__lookupGetter__',
  '__lookupSetter__',
  'hasOwnProperty',
  'propertyIsEnumerable',
  'isPrototypeOf',
  'toString',
  'valueOf',
  'toLocaleString'
]
 
function hasMethod(obj, name) {
  const desc = Object.getOwnPropertyDescriptor(obj, name)
  return !!desc && typeof desc.value === 'function'
}
 
function getInstanceMethodNames(obj, stop) {
  let array = []
  let proto = Object.getPrototypeOf(obj)
  while (proto && proto !== stop) {
    Object.getOwnPropertyNames(proto).forEach(name => {
      if (excluded.indexOf(name) === -1) {
        if (hasMethod(proto, name)) {
          array.push(name)
        }
      }
    })
    proto = Object.getPrototypeOf(proto)
  }
  return array
}
 
const getAllKeys = obj => {
  const methods = getInstanceMethodNames(obj)
  const keys = Object.keys(obj)
  return uniq(methods.concat(keys))
}
 
module.exports = getAllKeys