Last active
December 11, 2015 01:49
-
-
Save ghalimi/4526451 to your computer and use it in GitHub Desktop.
IMAGINARY Function
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
// Copyright (c) 2012 Sutoiku, Inc. (MIT License) | |
function IMAGINARY(inumber) { | |
// Return 0 if inumber is equal to 0 | |
if (inumber === 0 || inumber === '0') return 0; | |
// Handle special cases | |
if (['i', 'j'].indexOf(inumber) >= 0) return 1; | |
// Normalize imaginary coefficient | |
inumber = inumber.replace('+i', '+1i').replace('-i', '-1i').replace('+j', '+1j').replace('-j', '-1j'); | |
// Lookup sign | |
var plus = inumber.indexOf('+'); | |
var minus = inumber.indexOf('-'); | |
if (plus === 0) plus = inumber.indexOf('+', 1); | |
if (minus === 0) minus = inumber.indexOf('-', 1); | |
// Lookup imaginary unit | |
var last = inumber.substring(inumber.length - 1, inumber.length); | |
var unit = (last === 'i' || last === 'j') | |
if (plus >= 0 || minus >= 0) { | |
// Return error if imaginary unit is neither i nor j | |
if (!unit) return '#NUM!'; | |
// Return imaginary coefficient of complex number | |
if (plus >= 0) { | |
return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? | |
'#NUM!' : | |
Number(inumber.substring(plus + 1, inumber.length - 1)); | |
} else { | |
return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? | |
'#NUM!' : | |
-Number(inumber.substring(minus + 1, inumber.length - 1)); | |
} | |
} else { | |
if (unit) { | |
return (isNaN(inumber.substring(0, inumber.length - 1))) ? '#NUM!' : inumber.substring(0, inumber.length - 1); | |
} else { | |
return (isNaN(inumber)) ? '#NUM!' : 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment