GPTScript / AiScript

A Minimal, Full-Stack, Tool-Assisted Language. Native to Browsers and Bun. Strictly & Strongly-Typed.
https://github.com/GPTScript/AiScript
Mozilla Public License 2.0
9 stars 1 forks source link

`Object._trim(obj)` to remove `undefined` values #39

Open coolaj86 opened 2 years ago

coolaj86 commented 2 years ago
var x = {
  foo: undefined,
  bar: undefined,
  baz: undefined,
  qux: 'quux',
};

var y = Object._trim(x);
// { qux: 'quux' }

Rationalé

Depending on how the rest of the language is implemented, this may not be necessary.

However, often times you'll want and expect undefined values to be ignored, but instead they get stringified or cause an error, such as with:

Considerations

This has to be implemented with care to keep type safety and to not break JIT optimizations.

For example:

Option A

Object._trim = function (obj) {
    let copied = {};
    for (let k in obj) {
        if ('undefined' !== typeof obj[k]) {
            copied[k] = obj[k];
        }
    }
    return copied;
}

Option B

Object._trim = function (obj) {
    for (let k in obj) {
        if ('undefined' === typeof obj[k]) {
            delete obj[k];
        }
    }
    return obj;
}