diff --git a/snippets/functions.md b/snippets/functions.md new file mode 100644 index 000000000..7c3856cee --- /dev/null +++ b/snippets/functions.md @@ -0,0 +1,18 @@ +### functions + +Returns an array of function property names from own enumerable properties of object. + +Use `Object.keys(obj)` to iterate over the object's own properties, `Array.filter()` to keep only those that are functions. + +```js +const functions = obj => + Object.keys(obj).filter(key => typeof obj[key] === 'function'); +``` + +```js +function Foo() { + this.a = () => 1; + this.b = () => 2; +} +functions(new Foo); // ['a', 'b'] +``` diff --git a/snippets/functionsIn.md b/snippets/functionsIn.md new file mode 100644 index 000000000..cc0028493 --- /dev/null +++ b/snippets/functionsIn.md @@ -0,0 +1,20 @@ +### functionName + +Returns an array of function property names from own and inherited enumerable properties of object. + +Use `Object.keys(obj)` and `Object.get.PrototypeOf(obj)` to iterate over the object's own and inherited properties, `Array.filter()` to keep only those that are functions. +Use the spread operator (`...`) to combine all returned property names into one array. + +```js +const functionsIn = obj => + [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))].filter(key => typeof obj[key] === 'function'); +``` + +```js +function Foo() { + this.a = () => 1; + this.b = () => 2; +} +Foo.prototype.c = () => 3; +functionsIn(new Foo); // ['a', 'b', 'c'] +``` diff --git a/tag_database b/tag_database index 353f5fda5..812a08a5c 100644 --- a/tag_database +++ b/tag_database @@ -51,6 +51,8 @@ forEachRight:array,function formatDuration:date,math,string,utility fromCamelCase:string functionName:function,utility +functions:object,function +functionsIn:object,function gcd:math,recursion geometricProgression:math getDaysDiffBetweenDates:date