Skip to content

Instantly share code, notes, and snippets.

@JustenRickert
Created August 20, 2018 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustenRickert/4ceeb1f8b116c5c06a42997fd68ba09e to your computer and use it in GitHub Desktop.
Save JustenRickert/4ceeb1f8b116c5c06a42997fd68ba09e to your computer and use it in GitHub Desktop.

updateIn/updateInto

By Procedure

const byProcedure = <T>(arrays: T[][], update: { i: number; j: number; value: T }) => {
  const retArr: T[][] = [];
  for (const i in arrays) {
    retArr.push([]);
    for (const j in arrays[i]) {
      if (Number(i) === update.i && Number(j) === update.j) {
        retArr[i].push(update.value);
      } else {
        retArr[i].push(arrays[i][j]);
      }
    }
  }
  return retArr;
};
{ total_runtime: 1557,
  total_step_runtime: 1544,
  average_step_runtime: 15.44,
  total_off_baseline: 1555,
  total_step_off_baseline: 1544,
  average_step_off_baseline: 15.44 }

By Nested Map

const byNestedMap = <T>(arrays: T[][], update: { i: number; j: number; value: T }) =>
  arrays.map(
    (array, i) =>
      update.i === i ? array.map((a, j) => (update.j === j ? update.value : a)) : array,
  );
{ total_runtime: 5,
  total_step_runtime: 4,
  average_step_runtime: 0.04,
  total_off_baseline: 3,
  total_step_off_baseline: 4,
  average_step_off_baseline: 0.04 }

By Lodash’s Update

const byLodashUpdate = (
  data: number[][],
  { i, j, value }: { i: number; j: number; value: number },
) => update(data, `[{i}][{j}]`, constant(value));
{ total_runtime: 2,
  total_step_runtime: 1,
  average_step_runtime: 0.01,
  total_off_baseline: 0,
  total_step_off_baseline: 1,
  average_step_off_baseline: 0.01 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment