<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hamidreza Nateghi on Medium]]></title>
        <description><![CDATA[Stories by Hamidreza Nateghi on Medium]]></description>
        <link>https://medium.com/@nateghi?source=rss-70f0bd42d7f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FBbHDqLL8esM0KR833WGtg.jpeg</url>
            <title>Stories by Hamidreza Nateghi on Medium</title>
            <link>https://medium.com/@nateghi?source=rss-70f0bd42d7f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:46:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nateghi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to write Clamp function in JavaScript]]></title>
            <link>https://medium.com/@nateghi/how-to-write-clamp-function-in-javascript-d9ce7431e54c?source=rss-70f0bd42d7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9ce7431e54c</guid>
            <category><![CDATA[clamp]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hamidreza Nateghi]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 18:26:17 GMT</pubDate>
            <atom:updated>2023-09-21T18:26:17.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MvcY29Cxk42s85e0" /><figcaption>Photo by <a href="https://unsplash.com/@mattartz?utm_source=medium&amp;utm_medium=referral">Matt Artz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A “clamp” function is a mathematical or programming function that limits the range of a value within a specified minimum and maximum boundary. It ensures that a value does not fall below the minimum or exceed the maximum allowed range. The term “clamp” is often used in computer programming and mathematics to describe this behavior.</p><p>Let’s create our function that takes three parameters: number for the value, lower for the lower bound, and upper for the upper bound.</p><p>If the number exceeds the upper value, we assign it the upper value. Similarly, if the number falls below the lower value, we assign it the lower value. This is how we constrain the number within the specified range.</p><pre>function clamp(number, lower, upper) {<br>  number = number &lt; lower ? lower : number<br>  number = number &gt; upper ? upper : number<br><br>  return number<br>}</pre><p>In the first step, we simply pick the larger value between number and lower. So, we can use math to handle this:</p><pre>function clamp(number, lower, upper) {<br>  number = Math.max(number, lower)<br>  number = number &gt; upper ? upper : number<br><br>  return number<br>}</pre><p>Similarly, in the second step, we select the smaller value between number and upper:</p><pre>function clamp(number, lower, upper) {<br>  number = Math.max(number, lower)<br>  number = Math.min(number, upper)<br><br>  return number<br>}</pre><p>When we put it all together, we get:</p><pre>function clamp(number, lower, upper) {<br>  return Math.min(Math.max(number, lower), upper)<br>}</pre><p>We must ensure that all our values are valid numbers:</p><pre>function clamp(number, lower, upper) {<br>  if (typeof number !== &#39;number&#39; || typeof lower !== &#39;number&#39; || typeof upper !== &#39;number&#39;) {<br>    throw new Error(&#39;All inputs must be valid numbers.&#39;)<br>  }<br>  <br>  return Math.min(Math.max(number, lower), upper)<br>}</pre><p>For some strange reasons, even NaN is counted as a number. So, we should also skip that. We can make another function to check if something is a number or not:</p><pre>function isNumber(number) {<br>  return typeof number === &#39;number&#39; &amp;&amp; !isNaN(number)<br>}<br><br>function clamp(number, lower, upper) {<br>  if (!isNumber(number) || !isNumber(lower) || !isNumber(upper)) {<br>    throw new Error(&#39;All inputs must be valid numbers.&#39;)<br>  }<br>  <br>  return Math.min(Math.max(number, lower), upper)<br>}</pre><p>In JavaScript, arguments is an array-like object accessible inside functions that contains the values of the arguments passed to that function.</p><p>We can convert this object into an array using Array.from, and then we can use the every method to check if all the values in the resulting array are numbers.</p><p>The every() method of Array instances tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.</p><pre>function isNumber(number) {<br>  return typeof number === &#39;number&#39; &amp;&amp; !isNaN(number)<br>}<br><br>function clamp(number, lower, upper) {<br>  if (!Array.from(arguments).every(isNumber)) {<br>    throw new Error(&#39;All inputs must be valid numbers.&#39;)<br>  }<br>  <br>  return Math.min(Math.max(number, lower), upper)<br>}</pre><p>To ensure that the lower value is smaller than the upper value in our function, we can add a simple conditional check and swap the values if necessary:</p><pre>function isNumber(number) {<br>  return typeof number === &#39;number&#39; &amp;&amp; !isNaN(number)<br>}<br><br>function clamp(number, lower, upper) {<br>  if (!Array.from(arguments).every(isNumber)) {<br>    throw new Error(&#39;All inputs must be valid numbers.&#39;)<br>  }<br><br>  if (lower &gt; upper) {<br>    [lower, upper] = [upper, lower]<br>  }<br>  <br>  return Math.min(Math.max(number, lower), upper)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9ce7431e54c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Donut Chart using Material UI CircularProgress]]></title>
            <link>https://medium.com/@nateghi/material-ui-donut-chart-using-circularprogress-ea161c8fc27f?source=rss-70f0bd42d7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea161c8fc27f</guid>
            <category><![CDATA[circular-progress-bar]]></category>
            <category><![CDATA[material-ui]]></category>
            <category><![CDATA[donut-chart]]></category>
            <dc:creator><![CDATA[Hamidreza Nateghi]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 21:32:24 GMT</pubDate>
            <atom:updated>2023-08-17T21:36:27.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lDQpsrTe9pADYvQc" /><figcaption>Photo by <a href="https://unsplash.com/@sharonp?utm_source=medium&amp;utm_medium=referral">Sharon Pittaway</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s say we’re trying to make a donut chart using the <a href="https://mui.com/material-ui/react-progress/">CircularProgress</a> component from Material UI.</p><p>Because donut charts don’t have animated colors, we’ll apply the same approach to this element by using the variant=&#39;determinate&#39; property.</p><p>Let’s use 3 progress elements:</p><pre>&lt;div&gt;<br>  &lt;CircularProgress<br>    variant=&quot;determinate&quot;<br>    value={20}<br>  /&gt;<br>  &lt;CircularProgress<br>    variant=&quot;determinate&quot;<br>    value={50}<br>  /&gt;<br>  &lt;CircularProgress<br>    variant=&quot;determinate&quot;<br>    value={30}<br>  /&gt;<br>&lt;/div&gt;</pre><p>First, stack all three CircularProgress components on top of each other. To achieve this, set the position of each to absolute, and give the wrapper element a position of relative.</p><pre>const StyledCircularProgress = styled(CircularProgress)({<br>  position: &quot;absolute&quot;<br>});<br><br>&lt;Box sx={{ position: &quot;relative&quot; }}&gt;<br>  &lt;StyledCircularProgress<br>    variant=&quot;determinate&quot;<br>    value={20}<br>  /&gt;<br>  &lt;StyledCircularProgress<br>    variant=&quot;determinate&quot;<br>    value={50}<br>  /&gt;<br>  &lt;StyledCircularProgress<br>    variant=&quot;determinate&quot;<br>    value={30}<br>  /&gt;<br>&lt;/Box&gt;</pre><p>By default, CircularProgress has a rotation applied to it which makes it start from the top. For the second and third CircularProgress, we want them to start where the first one ended. To do this, we need to modify the rotation for the second and third CircularProgress components.</p><p>To determine where the next color should begin, calculate the percentage of progress that is colored. For example, let’s say the first color covers 20% of the progress. We need to convert this percentage to degrees to match the circular layout. If we consider 360 degrees in a full circle, 20% corresponds to 72 degrees. However, due to the default rotation, we need to adjust this value. Subtracting 90 degrees accounts for the starting point, resulting in -18 degrees for the second color.</p><pre>const firstDeg = (a / 100) * 360 - 90;</pre><p>For the third color, we apply a similar technique, but this time we need to add the values from both the first and second colors. This combination gives us the starting point for coloring the third section of the progress.</p><pre>const secondDeg = (((a + b) / 100) * 360).toFixed(2) - 90;</pre><p>We’re experiencing issues with fraction to decimal calculations in JavaScript, that’s why we used toFixed(2).</p><p>This rotation property is added directly to the element’s style, not its classes. So, you can override it using inline styling. We also give each progress a different color to see how it looks.</p><pre>function App() {<br>  return &lt;StatusCircle a={20} b={50} c={30} /&gt;<br>}<br><br>function StatusCircle({ a, b, c }) {<br>  const firstDeg = (a / 100) * 360 - 90;<br>  const secondDeg = (((a + b) / 100) * 360).toFixed(2) - 90;<br><br>  return (<br>    &lt;Box sx={{ position: &quot;relative&quot; }}&gt;<br>      &lt;StyledCircularProgress<br>        variant=&quot;determinate&quot;<br>        sx={{ color: &quot;red&quot; }}<br>        value={a}<br>      /&gt;<br>      &lt;StyledCircularProgress<br>        variant=&quot;determinate&quot;<br>        sx={{ color: &quot;green&quot; }}<br>        style={{ transform: `rotate(${firstDeg}deg)` }}<br>        value={b}<br>      /&gt;<br>      &lt;StyledCircularProgress<br>        variant=&quot;determinate&quot;<br>        sx={{ color: &quot;blue&quot; }}<br>        style={{ transform: `rotate(${secondDeg}deg)` }}<br>        value={c}<br>      /&gt;<br>    &lt;/Box&gt;<br>  );<br>}</pre><p>You can use this same approach for more than three colors. Just remember to calculate the degrees correctly for each color.</p><figure><img alt="Material UI Donut Chart using CircularProgress" src="https://cdn-images-1.medium.com/max/518/1*fRHS8a38ONIo38v-L9FiFw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea161c8fc27f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing Modal Issues: Two Solutions to Event Bubbling]]></title>
            <link>https://medium.com/@nateghi/fixing-modal-issues-two-solutions-to-event-bubbling-2a3540ad39c0?source=rss-70f0bd42d7f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a3540ad39c0</guid>
            <category><![CDATA[dialog]]></category>
            <category><![CDATA[event-bubbling]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[modal]]></category>
            <dc:creator><![CDATA[Hamidreza Nateghi]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 12:02:31 GMT</pubDate>
            <atom:updated>2023-08-17T21:36:47.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0H1yTYzR2VmKbP2q" /><figcaption>Photo by <a href="https://unsplash.com/@amyshamblen?utm_source=medium&amp;utm_medium=referral">Amy Shamblen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Fix Modal Issues: Two Solutions to Event Bubbling</h3><p>Suppose we have a component as shown below:</p><pre>function UserCard() {<br>  const [open, setOpen] = useState(false);<br><br>  const onDialogClose = () =&gt; setOpen(false)<br><br>  return (<br>    &lt;Box onClick={() =&gt; setOpen(true)}&gt;<br>      User<br>      &lt;UserDialog open={open} onClose={onDialogClose} /&gt;<br>    &lt;/Box&gt;<br>  );<br>};</pre><p>When you click on the Box, the dialog appears.</p><p>Here’s the component for the dialog:</p><pre>function UserDialog({open, onClose}) {<br>  return (<br>    &lt;Dialog open={open}&gt;<br>      &lt;IconButton onClick={onClose}&gt;<br>        &lt;CloseIcon /&gt;<br>      &lt;/IconButton&gt;<br>    &lt;/Dialog&gt;<br>  );<br>};</pre><p>You might think that when you click on the close button of the dialog, the dialog should close. However, it doesn’t happen. Why is that?</p><p>Because clicking the close button triggers a click event, which can also bubble up and inadvertently trigger a click event on the parent element. This results in the execution of the onClick={() =&gt; setOpen(true)} function on the element within UserCard.</p><p>To prevent this, you can use stopPropagation on the close button&#39;s click event. Here&#39;s how:</p><pre>function UserCard() {<br>  const [open, setOpen] = useState(false);<br><br>  const onDialogClose = (e) =&gt; {<br>    e.stopPropagation();<br>    setOpen(false);<br>  }<br><br>  return (<br>    &lt;Box onClick={() =&gt; setOpen(true)}&gt;<br>      User<br>      &lt;UserDialog open={open} onClose={onDialogClose} /&gt;<br>    &lt;/Box&gt;<br>  );<br>};</pre><blockquote>The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.<br>- Mozilla</blockquote><p>If you prefer not to use stopPropagation, you can simply place the UserDialog outside the Box element. This way, the dialog won&#39;t be a direct child of the box element anymore. Here&#39;s how you can do it:</p><pre>function UserCard() {<br>  const [open, setOpen] = useState(false);<br><br>  const onDialogClose = () =&gt; setOpen(false)<br><br>  return (<br>    &lt;Box onClick={() =&gt; setOpen(true)}&gt;<br>      User<br>    &lt;/Box&gt;<br>    &lt;UserDialog open={open} onClose={onDialogClose} /&gt;<br>  );<br>};</pre><p>For this article, I used <a href="https://mui.com/material-ui/">Material UI</a> elements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a3540ad39c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>