From bd8551d78aed83d7b84514076126fbed845d748e Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 12 Jan 2018 13:55:49 +0200 Subject: [PATCH] Add transform --- snippets/transform.md | 17 +++++++++++++++++ tag_database | 1 + 2 files changed, 18 insertions(+) create mode 100644 snippets/transform.md diff --git a/snippets/transform.md b/snippets/transform.md new file mode 100644 index 000000000..de8d1236d --- /dev/null +++ b/snippets/transform.md @@ -0,0 +1,17 @@ +### transform + +Applies a function against an accumulator and each key in the object (from left to right). + +Use `Object.keys(obj)` to iterate over each key in the object, `Array.reduce()` to call the apply the specified function against the given accumulator. + +```js +const transform = (obj, fn, acc) => + Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); +``` + +```js +transform({ 'a': 1, 'b': 2, 'c': 1 }, (r, v, k) => { + (r[v] || (r[v] = [])).push(k); + return r; +}, {}); // { '1': ['a', 'c'], '2': ['b'] } +``` diff --git a/tag_database b/tag_database index d9ad2a94e..e70eef4a2 100644 --- a/tag_database +++ b/tag_database @@ -181,6 +181,7 @@ tomorrow:date toOrdinalSuffix:utility,math toSafeInteger:math toSnakeCase:string,regexp +transform:object,array truncateString:string truthCheckCollection:object,logic,array unescapeHTML:string,browser