Skip to content

Instantly share code, notes, and snippets.

@alexeden
Last active April 17, 2019 18:01
Show Gist options
  • Select an option

  • Save alexeden/b6c11ff6350b26852c4ec4be525b0db6 to your computer and use it in GitHub Desktop.

Select an option

Save alexeden/b6c11ff6350b26852c4ec4be525b0db6 to your computer and use it in GitHub Desktop.
Answers to Finish the Function data transformation problems

Finish the Function: Data transformations

Sum of Numbers

const sum = (...nums) => nums.reduce((accum, x) => accum + x, 0);

Combine Strings

const joinStrings = (...strings) => strings.reduce((accum, s) => accum + s, '');

Combine Arrays

const joinArrays = (...lists) => list.reduce((accum, x) => [...accum, ...x], []);

Merge Objects

const mergeObjects = (...objs) => objs.reduce((accum, x) => ({ ...accum, ...x }), {});

Object from Pairs

const objFromPairs = (...pairs) => pairs.reduce((accum, [k, v]) => ({ ...accum, [k]: v }), {});

Pairs from Objects

const pairsFromObj = obj => Object.entries(obj);

Derive map

const map = (fn, list) => list.reduce((accum, x) => ([ ...accum, fn(x) ]), []);

Derive filter

const filter = (fn, list) => list.reduce((accum, x) => fn(x) ? [...accum, x] : accum, []);

Strings to Object of Numbers

const strsToObj = (...strs) => strs.reduce((obj, str) => ({ ...obj, [str]: 0 }), {});

Reverse Keys

const reverseKeys = obj => Object.entries(obj).reduce(
  (accum, [k, v]) => ({
    ...accum,
    [k.split('').reverse().join('')]: v
  }),
  {}
);

Key-Value Swap

const swapKeyValues = obj => Object.entries(obj).reduce(
  (accum, [k, v]) => ({ ...accum, [v]: k }),
  {}
);

Omit Keys

const omitKeys = (keys, obj) => Object.entries(obj).reduce(
  (accum, [k, v]) => keys.includes(k)
    ? accum
    : { ...accum, [k]: v },
  {}
);

Capitalization

const capitalize = ([firstLetter = '', ...rest] = '') => `${firstLetter.toUpperCase()}${rest.join('')}`;

Map by Prop

const mapByProp = (prop, list) => list.reduce(
  (accum, obj) => ({ ...accum, [obj[prop]]: obj }),
  {}
);

Multi Filter

const multiFilter = (fns, list) => list.filter(x => fns.every(fn => fn(x)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment