Skip to content

Instantly share code, notes, and snippets.

@horiuchie
Created December 11, 2019 08:33
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 horiuchie/6af52ba67d2f16002a685befb7fb7afa to your computer and use it in GitHub Desktop.
Save horiuchie/6af52ba67d2f16002a685befb7fb7afa to your computer and use it in GitHub Desktop.
update or append element like get_or_create of Django.
const updateOrAppend = R.curry((comp, value, list) => {
const index = R.findIndex(comp, list);
return index < 0 ? R.append(value, list) : R.update(index, value, list);
});
// Usage
const family = [{ name: 'taro', age: 30 }, { name: 'jiro', age: 28 }, { name: 'saburo', age: 26 }];
// 1. update taro in family if included.
updateOrAppend(R.propEq('name', 'taro'), { name: 'taro', age: 32 }, family);
// => [{"age": 32, "name": "taro"}, {"age": 28, "name": "jiro"}, {"age": 26, "name": "saburo"}]
// 1. add shiro to family if not included.
const receiveData = { name: 'shiro', age: 24 };
updateOrAppend(R.propEq('name', 'shiro'), receiveData, family);
// => [{"age": 30, "name": "taro"}, {"age": 28, "name": "jiro"}, {"age": 26, "name": "saburo"}, {"age": 24, "name": "shiro"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment