From 2412388aadcfb2c7f157f2ac28923e915bbf4308 Mon Sep 17 00:00:00 2001 From: zyd Date: Tue, 24 May 2022 14:56:07 +0900 Subject: [PATCH] add method forEach --- README.md | 3 +-- ramda/__init__.py | 1 + ramda/forEach.py | 14 ++++++++++++ test/test_forEach.py | 52 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 68 insertions(+), 2 deletions(-) create mode 100644 ramda/forEach.py create mode 100644 test/test_forEach.py diff --git a/README.md b/README.md index 2b78eb9..867af13 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@ # python_ramda - This is a repo try to copy in python. [![linting: pylint](https://img.shields.io/badge/linting-pylint-yellowgreen)](https://github.com/PyCQA/pylint) @@ -195,7 +194,7 @@ R.equals(float('nan'), float('nan')) # True - [ ] findLastIndex - [x] 0.1.2 flatten - [x] 0.1.2 flip -- [ ] forEach +- [x] forEach - [ ] forEachObjIndexed - [ ] fromPairs - [x] 0.1.2 groupBy diff --git a/ramda/__init__.py b/ramda/__init__.py index 6c1d97b..fc0f17d 100644 --- a/ramda/__init__.py +++ b/ramda/__init__.py @@ -25,6 +25,7 @@ from .find import find from .flatten import flatten from .flip import flip +from .forEach import forEach from .groupBy import groupBy from .gt import gt from .gte import gte diff --git a/ramda/forEach.py b/ramda/forEach.py new file mode 100644 index 0000000..f9380d0 --- /dev/null +++ b/ramda/forEach.py @@ -0,0 +1,14 @@ +from .private._checkForMethod import _checkForMethod +from .private._curry2 import _curry2 + + +def inner_forEach(fn, arr): + length = len(arr) + idx = 0 + while idx < length: + fn(arr[idx]) + idx += 1 + return arr + + +forEach = _curry2(_checkForMethod('forEach', inner_forEach)) diff --git a/test/test_forEach.py b/test/test_forEach.py new file mode 100644 index 0000000..9b1982c --- /dev/null +++ b/test/test_forEach.py @@ -0,0 +1,52 @@ + +import unittest + +import ramda as R + +""" +https://github.com/ramda/ramda/blob/master/test/forEach.js +""" + +arr = [{'x': 1, 'y': 2}, {'x': 100, 'y': 200}, {'x': 300, 'y': 400}, {'x': 234, 'y': 345}] + + +class TestForEach(unittest.TestCase): + def test_performes_the_passed_in_function_on_each_element_of_the_list(self): + sideEffect = {} + + def fn(elem): + nonlocal sideEffect + sideEffect[elem['x']] = elem['y'] + R.forEach(fn, arr) + self.assertEqual(sideEffect, {1: 2, 100: 200, 300: 400, 234: 345}) + + def test_returns_the_original_list(self): + s = '' + + def fn(obj): + nonlocal s + s += str(obj['x']) + self.assertEqual(arr, R.forEach(fn, arr)) + self.assertEqual(s, '1100300234') + + def test_handles_empty_list(self): + self.assertEqual([], R.forEach(lambda x: x * x, [])) + + def test_dispatches_to_forEach_method(self): + dispatched = False + + def fn(): + return + + class DummyList: + def forEach(this, callback): + nonlocal dispatched + dispatched = True + self.assertEqual(fn, callback) + + R.forEach(fn, DummyList()) + self.assertEqual(True, dispatched) + + +if __name__ == '__main__': + unittest.main()