just icon indicating copy to clipboard operation
just copied to clipboard

just-omit only handles root level omissions

Open cycle4passion opened this issue 2 years ago • 4 comments

easily could change to use code like just-safe-set, then it will handle nested objects/arrays. Working from the just-safe-set code

Changes

  • new function name/export name: omit and dropped the value param
  • obj[lastProp] = value becomes delete obj[lastProp]
  • if used on array, delete obj[lastProp] puts in null, so check for array and handle with obj.splice(parseInt(lastProp), 1)
module.exports = omit;

/*
var obj = {a: 3, b: {c:5, d:7}, e:[1,2,3]};
omit(obj, 'a'); // {b: {c:5, d:7}, e:[1,2,3]};
omit(obj, 'b.c'); // {a:3, b: {d:7}, e:[1,2,3]};
omit(obj, 'e.1'); // {a: 3, b: {c:5, d:7}, e:[1,3]};
*/

function omit(obj, propsArg) {
  var props, lastProp;
  if (Array.isArray(propsArg)) {
    props = propsArg.slice(0);
  }
  if (typeof propsArg == 'string') {
    props = propsArg.split('.');
  }
  if (typeof propsArg == 'symbol') {
    props = [propsArg];
  }
  if (!Array.isArray(props)) {
    throw new Error('props arg must be an array, a string or a symbol');
  }
  lastProp = props.pop();
  if (!lastProp) {
    return false;
  }
  prototypeCheck(lastProp);
  var thisProp;
  while ((thisProp = props.shift())) {
    prototypeCheck(thisProp);
    if (typeof obj[thisProp] == 'undefined') {
      obj[thisProp] = {};
    }
    obj = obj[thisProp];
    if (!obj || typeof obj != 'object') {
      return false;
    }
  }
  if (Array.isArray(obj)) {
    obj.splice(parseInt(lastProp), 1);
  } else { 
    delete obj[lastProp];
  }
  return true;
}

function prototypeCheck(prop) {
  // coercion is intentional to catch prop values like `['__proto__']`
  if (prop == '__proto__' || prop == 'constructor' || prop == 'prototype') {
    throw new Error('setting of prototype values not supported');
  }
}

cycle4passion avatar Nov 27 '22 23:11 cycle4passion

Thanks, this is nice. Feel free to put up a PR including new tests

angus-c avatar Dec 29 '22 00:12 angus-c

I will take a stab at it. Will be my first PR. Should it be a new function renamed as "just-safe-omit" to match up with just-safe-[get/set]? As you know both safe functions dig deep in nesting. Seems like the other functions (like just-pick) are all aimed at root level object and array methods? Happy to leave it name just-omit if you think thats better.

cycle4passion avatar Dec 30 '22 18:12 cycle4passion

A new function sounds good. How about just-deep-omit?

angus-c avatar Dec 30 '22 19:12 angus-c

Awesome

cycle4passion avatar Dec 30 '22 21:12 cycle4passion