Last active
February 11, 2018 01:17
-
-
Save rivernews/f1b52d2437a2d4ca83f12b7c01526380 to your computer and use it in GitHub Desktop.
Integer String Sum
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
{% extends 'base/html5_base.html' %} | |
{% load staticfiles %} | |
{% block content %} | |
<md-content data-ng-controller="techChController"> | |
<md-card > | |
<md-card-content> | |
<a class="md-headline">Integer Sum from String</a><br> | |
<a> This page demostrates our solution to the task for the Academic Innovation Summer Internship Program.<br> | |
User will input some arbitrary text. If there is any number within the text, the numbers will be extracted and sum together.<br> | |
The extracted numbers and sum result will be shown below in realtime.</a> | |
<form> | |
<md-input-container class="md-input-has-placeholder md-block" > | |
<label for="user_input" >Plesae type in here ...</label> | |
<input size="auto" type="text" id="user_input" data-ng-model="user_input" > | |
Extracted Numbers:<br><a data-ng-bind="process_str(user_input)['nums']"></a> | |
<p style="margin-top: 20px;" class=""> | |
<a class="md-title">Result</a><br> | |
<a data-ng-bind="process_str(user_input)['sum']"></a><br> | |
</p> | |
</md-input-container> | |
</form> | |
<a class="md-headline">Code Snippet</a><br> | |
<script src="https://gist.github.com/rivernews/f1b52d2437a2d4ca83f12b7c01526380.js"></script> | |
</md-card-content> | |
</md-card> | |
</md-content> | |
<script> | |
app.controller("techChController", function($scope){ | |
// initializtion | |
$scope.user_input = ""; | |
// process user input in realtime | |
/* only considering integers in string. Future work could be detecting floating values. */ | |
$scope.process_str = function(str){ | |
// clean string and leave numbers only | |
var temp_str = str.replace(/[^\d-]/g, "_"); | |
// extract integers out | |
var re = /((\-)?([1-9])([0-9]){0,})/g; | |
var matches = temp_str.match(re); | |
if (matches == null){ // no match yet | |
return { | |
"nums": "(Empty)", | |
"sum": "(Empty)", | |
}; | |
} | |
// show all numbers | |
var output = ""; | |
for (var i = 0; i < matches.length; i++){ | |
output += matches[i] + ", "; | |
} | |
// sum all numbers | |
var sum = matches.reduce( (a, b) => parseInt(a) + parseInt(b) ); | |
return { | |
"nums": output, | |
"sum": sum, | |
}; | |
} | |
}); | |
</script> | |
{% endblock %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment