JSFiddle - React, Tailwind, and code Playground

by jrab227

JavaScript

function splitIndex(index) {
	return index.split('/');
}

function lens(index, modifier, state) {
	let keys = splitIndex(index);
  if (keys.length === 1) {
  	let current = state[keys[0]];
    state[keys[0]] = modifier(current);
    return {
    	value: current,
      state: state
    }
  }
  
  let newV = lens(keys.slice(1).join('/'), modifier, state[keys[0]]);
  state[keys[0]] = newV.state;
  return {
  	value: newV.value,
    state: state
  };
}

let k = {a: {b: {c: 10}}};

let result = lens('a/b/c', function(v) { return v + 10}, k);

console.log(result)