Ticket #20419: map_filter.patch

File map_filter.patch, 1.4 KB (added by Sylvain Leroux, 11 years ago)
  • django/template/defaultfilters.py

    diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
    index 88526e5..0f5870c 100644
    a b def pprint(value):  
    888888        return pformat(value)
    889889    except Exception as e:
    890890        return "Error in formatting: %s" % force_text(e, errors="replace")
     891
     892###################
     893# MATH            #
     894###################
     895
     896@register.filter("map")
     897def map_filter(value, src_min, src_max, dst_min, dst_max):
     898    """map the value from [src_min,src_max] range to [dst_min, dst_max]
     899    range.
     900
     901    Modeled after the corresponding map() function available (for
     902    example) in Processing http://processing.org/reference/map_.html
     903    """
     904    return dst_min + value * ( dst_max - dst_min) / ( src_max - src_min)
     905
  • tests/defaultfilters/tests.py

    diff --git a/tests/defaultfilters/tests.py b/tests/defaultfilters/tests.py
    index 21734fa..50e6ca8 100644
    a b class DefaultFiltersTests(TestCase):  
    656656        self.assertEqual(removetags(123, 'a'), '123')
    657657        self.assertEqual(striptags(123), '123')
    658658
     659    def test_map_filter(self):
     660        self.assertAlmostEqual(map_filter(0, 0, 100, 0, 1000), 0)
     661        self.assertAlmostEqual(map_filter(0, 0, 100, 1000, 0), 1000)
     662        self.assertAlmostEqual(map_filter(0, 100, 0, 0, 1000), 1000)
     663        self.assertAlmostEqual(map_filter(10, 0, 100, 0, 1000), 100)
Back to Top