Created
December 11, 2019 08:33
-
-
Save horiuchie/6af52ba67d2f16002a685befb7fb7afa to your computer and use it in GitHub Desktop.
update or append element like get_or_create of Django.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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