ProxyUndefined
Return default value for object properties that does not exists i.e is undefined.
Install
npm install proxy-undefined yarn add proxy-undefined
Usage
const optional optionalFn = ;// Or;
Why ProxyUndefined
When working with api's or objects, in some cases you may not know if a value exists in an object and it will result to doing something like
let requiredValue = SomeObjectname; if!requiredValue requiredValue = "Guest" // Or if!SomeObject requiredValue = "Guest"
With ProxyUndefined using Javascript Proxy Function, all undefined paths will be replaced with the value you set as default.
const optional optionalFn = ; let requiredValue = name;
Example
const optional = ; const data = message: "Hello World" { console; } { console; }; console;;// => Hello World data;// => Foo function was called //////////////////////////// Using data.name (undefined)console;// => undefined console;// => undefined console;// => John Doe //////////////////////////// Using data.message (defined)console;// => Hello World console;// => Hello World
Function Example
In Javascript if you call data.getFullName()
and getFullName
does not exists on the object we get an error.
with optionalFn
you can set a default function if the one being called does not exists.
// Using same data above.data;// => Bar function was called data;// => THIS WILL CAUSE AN ERROR// Error: data.getFullName is not a function // Using `optionalFn`;// => undefined// No Fatal Errors. ;// => John P. Doe// Default function ran instead. console;// => john@doe.com// If default is not a function, it is returned directly.
Fn: exists/optional
Checks if path exists in object else returns [default=undefined]
const exist = ; // is same as below, just an alias. const optional = ;
Fn: fnExists/optionalFn
Checks if function exists else returns [default=() => undefined]
const fnExist = ; // is same as below, just an alias. const optionalFn = ;
Hope you find this Useful. :)