How to access value inside String. Flutter/Dart - json

This is my code :
String text = snapshot.data[index];
var splitText = text.split("\n") ;
final jdata = jsonEncode(splitText[5]);
print(jdata);
which prints the String :
"RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}"
snapshot.data[index] contains :
I/flutter (14351): Code : LE-0000000002
I/flutter (14351): Description : test_01
I/flutter (14351): Organisation Unit : 01_01_04_01_SA - Shah Alam
I/flutter (14351): Date Reported : 18/09/2020
I/flutter (14351): Status : LE110 - Pending Approval
I/flutter (14351): RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}
my question is how do I access the value of "id".
Thanks!

I'm assuming that string is not changing in any condition other wise logic may fail..
void main() {
// actual string
// String x="RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}";
String x = snapshot.data[index];
// remove unwanted substring form string
List keyValues= x.replaceAll('RunHyperlink : {','').replaceAll('}','').replaceAll(', ',',').split(",");
//create map
Map map = {};
// run for loop to split key and value
for (var element in keyValues){
print(element.split(": ")[0]);
map.addAll({element.split(": ")[0] : element.split(": ")[1]});
}
// get the id balue
print(map['id']);
}

String temp;
const start = " id:";
const end = ",";
if (str.contains(start)) {
final startIndex = str.indexOf(start);
final endIndex = str.indexOf(end, startIndex + start.length);
temp = str.substring(startIndex + start.length, endIndex);
print("ID $temp");
}
or
Iterable<Match>? matches = RegExp(r' id\W*([a-z0-9\s]+,)').allMatches(str);
for (var m in matches) {
print(m.group(0));
}

Related

Get data from JSON in flutter

I am using the following code to verify stock data:
Future<Stock> verifyIfStockSymbolIsValid(String symbol) async {
final response =
await http.get('https://cloud.iexapis.com/stable/stock/$symbol/quote?token=my-token');
if (response.statusCode == 200) {
// Get Map from JSON.
Map data = json.decode(response.body);
print(data); // here the data (output below) is printed!
Map quoteData = data['quote'];
Stock stockQuote = Stock.fromJson(quoteData); // here should be the problem
return stockQuote;
} else {
return null;
}
}
The output looks like this:
I/flutter ( 9290): {symbol: XOM, companyName: Exxon Mobil Corp., primaryExchange: NEW YORK STOCK EXCHANGE, INC., calculationPrice: tops, open: null, openTime: null, openSource: official, close: null, closeTime: null, closeSource: official, high: null, highTime: 1608044090030, highSource: 15 minute delayed price, low: null, lowTime: 1608044281245, lowSource: IEX real time price, latestPrice: 42.52, latestSource: IEX real time price, latestTime: 10:09:34 AM, latestUpdate: 1608044974460, latestVolume: null, iexRealtimePrice: 42.52, iexRealtimeSize: 100, iexLastUpdated: 1608044974460, delayedPrice: null, delayedPriceTime: null, oddLotDelayedPrice: null, oddLotDelayedPriceTime: null, extendedPrice: null, extendedChange: null, extendedChangePercent: null, extendedPriceTime: null, previousClose: 42.22, previousVolume: 30595042, change: 0.3, changePercent: 0.00711, volume: null, iexMarketPercent: 0.01788127392568208, iexVolume: 65063, avgTotalVolume: 30683847, iexBidPrice: 41.99, iexBidSize: 100, iexAskPrice: 42.51, iexAskSize: 400, iexOpen: 42.475, iexOpenTime: 1608052428625, iexClose: 42.475, iexCloseTime: 1608052428625, marketCap: 179594243992, peRatio: 54.63, week52High: 65.66, week52Low: 29.54, ytdChange: -0.3405948289133432, lastTradeTime: 1608052428625, isUSMarketOpen: true}
E/flutter ( 9290): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 9290): Receiver: null
E/flutter ( 9290): Tried calling:
And my stock class is looking like that:
class Stock {
final String companyName;
final String symbol;
// The following are dynamic as using double generates an error
// when the API returns values with no decimal (e.g. 12 vs 12.0).
final dynamic latestPrice;
final dynamic low;
final dynamic high;
final dynamic week52High;
final dynamic change;
final dynamic changePercent;
final dynamic peRatio;
final dynamic previousClose;
// Default constructor.
Stock(this.companyName, this.symbol, this.latestPrice,
this.low, this.high, this.week52High, this.change,
this.changePercent, this.peRatio, this.previousClose);
// Named constructor, create object from JSON.
Stock.fromJson(Map<String, dynamic> json)
: companyName = (json['companyName'] != null ? json['companyName'] : ""),
symbol = (json['symbol'] != null ? json['symbol'] : ""),
latestPrice = (json['latestPrice'] != null ? json['latestPrice'] : 0.0),
low = (json['low'] != null ? json['low'] : 0.0),
high = (json['high'] != null ? json['high'] : 0.0),
week52High = (json['week52High'] != null ? json['week52High'] : 0.0),
change = (json['change'] != null ? json['change'] : 0.0),
changePercent = (json['changePercent'] != null ? json['changePercent'] : 0.0),
peRatio = (json['peRatio'] != null ? json['peRatio'] : 0.0),
previousClose = (json['previousClose'] != null ? json['previousClose'] : 0.0);
}
How can I solve this?
final data = json.decode(response.body) as Map;
print(data); // here the data (output below) is printed!
final quoteData = data['quote'] as Map;
Casting is imp , try this and let me know too..
replace only 3 lines above

Create JSON using for loop, Express.js

I'm newbie to express.js. I want to create a JSON using for loop. But the code returns object object. I don't know why. But for a single JSON, it returns as a JSON value. In this code, I have added a function to retrieve my JSON values from mongoDB. Please help me to complete this.
router.get('/', (req, res) => {
Followups.find({}).then(followupData => {
Staffs.find({}).then(staffData => {
Institutions.find({}).then(institutionData => {
var fcount = Object.keys(followupData).length;
var scount = Object.keys(staffData).length;
var icount = Object.keys(institutionData).length;
console.log(icount);
var jsonData = '';
function getStaffData(id) {
return staffData.filter(
function(staffData) {
return staffData._id == id;
}
);
}
function getInstitutionData(id) {
return institutionData.filter(
function(institutionData) {
return institutionData._id == id;
}
);
}
for (i=0; i<fcount; i++)
{
fstaffid = followupData[i].staffid;
fschoolid = followupData[i].schoolid;
staffDetails = getStaffData(fstaffid);
institutionDetails = getInstitutionData(fschoolid);
jsonData += {
staffname : staffDetails[0].achternaam + ' ' + staffDetails[0].voornaam + ' ' + staffDetails[0].tv,
staffplace : staffDetails[0].plaats,
staffphone : staffDetails[0].telefoon,
schoolname : institutionDetails[0].instellingsnaam,
schoolplace : institutionDetails[0].plaatsnaam,
schoolphone : institutionDetails[0].telefoonnummer,
notes : followupData[i].notes,
date : followupData[i].date,
created_at : followupData[i].created_at,
status : followupData[i].seen
}
}
console.log(jsonData);
res.render('followup', {followupData:followupData, jsonData: jsonData});
});
});
});
});
Problem solved by using concat
jsonData = jsonData.concat({
followupid : followupData[i]._id,
schoolid : followupData[i].schoolid,
staffid : followupData[i].staffid,
staffname : staffDetails[0].achternaam + ' ' + staffDetails[0].voornaam + ' ' + staffDetails[0].tv,
staffplace : staffDetails[0].plaats,
staffphone : staffDetails[0].telefoon,
schoolname : institutionDetails[0].instellingsnaam,
schoolplace : institutionDetails[0].plaatsnaam,
schoolphone : institutionDetails[0].telefoonnummer,
notes : followupData[i].notes,
date : followupData[i].date,
created_at : followupData[i].created_at,
status : followupData[i].seen
});
You can display the data of jsonData like:
console.log(JSON.stringify(jsonData));
object object means jsonData is a JSON object, you cannot display a JSON object directly. You must stringify it before doing this.
You may be able to find more about the issue after using JSON.stringify

json data parsing using retrofit and rxjava2 data display in Textview and TableLayout

JSON Data Parsing Using Retofit2 and Rxjava2. This Data get In ArrayList successfully. its ArrayList Size is Nine but its display only two Record in Table. After Two Record its Kotlin.NullPointerException.
JSON Data:
{"success":1,"salesGst":[{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"1","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"2778.75","TaxTotal":"2778.75","InvoiceType":"Retail Invoice","CGSTTotal":"0.0","PartyGST":"CDE","SGSTTotal":"0.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"1","ChallanDate":"2019-03-13 00:00:00","ChallanAmount":"2203.0","TaxTotal":"2118.5","InvoiceType":"Tax Invoice","CGSTTotal":"52.96","PartyGST":"CDE","SGSTTotal":"52.96","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"VIKAS","ChallanNo":"2","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"6975.0","TaxTotal":"6975.0","InvoiceType":"Retail Invoice","CGSTTotal":"0.0","PartyGST":null,"SGSTTotal":"0.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES MH","ChallanNo":"2","ChallanDate":"2019-03-13 00:00:00","ChallanAmount":"420.0","TaxTotal":"403.75","InvoiceType":"Tax Invoice","CGSTTotal":"0.0","PartyGST":"ABC","SGSTTotal":"0.0","IGSTTotal":"20.19"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"3","ChallanDate":"2019-03-14 00:00:00","ChallanAmount":"4788.0","TaxTotal":"4560.0","InvoiceType":"Tax Invoice","CGSTTotal":"114.0","PartyGST":"CDE","SGSTTotal":"114.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"4","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"241.9","TaxTotal":"230.38","InvoiceType":"Tax Invoice","CGSTTotal":"5.76","PartyGST":"CDE","SGSTTotal":"5.76","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"5","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"5563.68","TaxTotal":"5101.5","InvoiceType":"Tax Invoice","CGSTTotal":"231.28","PartyGST":"CDE","SGSTTotal":"231.28","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"6","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"13238.0","TaxTotal":"12459.25","InvoiceType":"Tax Invoice","CGSTTotal":"389.29","PartyGST":"CDE","SGSTTotal":"389.29","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES MH","ChallanNo":"7","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"2074.0","TaxTotal":"1975.0","InvoiceType":"Tax Invoice","CGSTTotal":"0.0","PartyGST":"ABC","SGSTTotal":"0.0","IGSTTotal":"98.75"}]}
Please Guide Me,After Getting How to Show in TableLayout.
In ArrayList Nine Record but in Table show only Two Record another seven record is not display. in third record taxtotal give kotlin.nullpointerException. what missing?
private fun displaySalesGSTData(salesGSt : List<SalesGST>) {
salesGST = SalesGST()
tvSalesCompanyName.setText(salesGSt.get(1).Cmp_Name)
tvGSTIN.setText(salesGSt.get(1).GSTIN)
val rowHeader = TableRow(this#Sales)
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"))
rowHeader.setLayoutParams(TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT))
val headerText = arrayOf<String>("Sr.No.", "Invoice Type", "Bill No.", "Bill Date", "Firm Name", "GST NO","TAX Total","CGST","SGST","IGST","Net Amount")
for (c in headerText)
{
val tv = TextView(this#Sales)
tv.setLayoutParams(TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT))
tv.setGravity(Gravity.CENTER)
// tv.setBackgroundResource(R.drawable.table_header)
tv.setTextColor(Color.parseColor("#3F51B5"))
tv.setTextSize(18F)
tv.setPadding(5, 5, 5, 5)
tv.setText(c)
rowHeader.addView(tv)
}
tableMarks.addView(rowHeader)
for (j in 0 until salesGSt.size)
{
/*val jsonObject1 = jsonArray.getJSONObject(j)
val date = jsonObject1.getString("ExamDate")
val inputFormatter1 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val date1 = inputFormatter1.parse(date)
val outputFormatter1 = SimpleDateFormat("dd-MMM-yyyy")
ExamDate = outputFormatter1.format(date1)*/
/* String replaceDate = date.replace("/Date(", "").replace(")/", "");
Long getDate = Long.valueOf(replaceDate);
ExamDate = dateFormat.format(getDate);*/
/*Subject = jsonObject1.getString("subject")
ExamName = jsonObject1.getString("ExamName")
TotalMark = jsonObject1.getLong("TotalMarks")
PassingMark = jsonObject1.getLong("PassingMarks")
Mark = jsonObject1.getLong("Marks")*/
var fName : String = salesGSt.get(j).FirmName!!
var invoice : String = salesGSt.get(j).InvoiceType!!
var bill_no : String = salesGSt.get(j).ChallanNo!!
var bill_date : String = salesGSt.get(j).ChallanDate!!
var gst_no : String = salesGSt.get(j).PartyGST!!
var tax_total : Double = salesGSt.get(j).TaxTotal!!.toDouble()
var cgst : String = salesGSt.get(j).CGSTTotal!!
var igst : String = salesGSt.get(j).IGSTTotal!!
var sgst : String = salesGSt.get(j).SGSTTotal!!
var net_amount : String = salesGSt.get(j).ChallanAmount!!
var sr : Int = j + 1
// dara rows
val row = TableRow(this#Sales)
row.setLayoutParams(TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT))
val colText = arrayOf<String>(sr.toString(),(invoice), bill_no, bill_date, fName, gst_no, tax_total.toString(),cgst,sgst,igst,net_amount)
for (text in colText)
{
val tv = TextView(this#Sales)
tv.setLayoutParams(TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT))
tv.setGravity(Gravity.CENTER)
// tv.setBackgroundResource(R.drawable.table_shape)
tv.setTextSize(18F)
tv.setTextColor(Color.parseColor("#3F51B5"))
tv.setPadding(5, 5, 5, 5)
tv.setText(text)
row.addView(tv)
}
tableMarks.addView(row)
}
}
The 3rd item, salesGst[2], is "PartyGST": null. Your json deserializer library won't handle non-null fields as it's written in Java. I assume you have a data class where PartGST is defined as non-null, yet the deserializer will still parse it as null. Therefore, when you access PartyGST then you will receive a NullPointerException because Kotlin is expecting it to be non-null. This is a good article, which explains in more detail:
I've trusted you! You promised no null pointer exceptions!
A solution to this would be to have two models. The DTO (for JSON response) where all fields are optional and your internal model (used by your app), where you define which fields you want to be optional. Then you can have a mapper to handle the case where a field is null in the DTO, but non-null in your internal model:
// Models for your API response
data class SalesGstsDTO(val gsts: List<GstDTO>)
data class GstDTO(val name: String?, val surname: String?)
// Internal models used by your app
data class SalesGsts(val gsts: List<Gst>)
data class Gst(val name: String, val surname: String?)
class SalesGstDTOMapper {
fun mapToSalesGsts(salesGstsDTO: SalesGstsDTO): SalesGsts {
val gsts = mutableListOf<Gst>()
salesGstsDTO.gsts.map {
val name = it.name ?: return#map // Skips this item. You could handle this how you wish
val surname = it.surname
val gst = Gst(name, surname)
gsts.add(gst)
}
return SalesGsts(gsts)
}
}
This also allows you to decouple your app from the JSON response.

remove duplicate entries while executing repeated job to save json data in mongo

I am having following structure currently present in my database, i am executing a service to fetch data from REST api and storing it to my database , so that i can use it to display it frequently on UI as like caching a data
db.countDetails.find().pretty()
{
"_id" : ObjectId("5670xxxx"),
"totalProjectCount" : 53,
"activeProjectCount" : 29,
"completedProjectCount" : 1,
"userCount" : 85
}
{
"_id" : ObjectId("5670ea97f14c717a903e8423"),
"totalProjectCount" : 48,
"activeProjectCount" : 41,
"completedProjectCount" : 0,
"userCount" : 123
}
My collection is going to remain same only values will be going to change, so please suggest me a way in which i can place the updated values in mongo and at the same time i can fetch data on my UI
my new values might be like
db.countDetails.find().pretty()
{
"_id" : ObjectId("5670xxxx"),
"totalProjectCount" : 23,
"activeProjectCount" : 17,
"completedProjectCount" : 1,
"userCount" : 60
}
{
"_id" : ObjectId("5670ea97f14c717a903e8423"),
"totalProjectCount" : 45,
"activeProjectCount" : 40,
"completedProjectCount" : 0,
"userCount" : 113
}
function to fetch data from REST api
def getCount(String companyName, String apiKey) {
//declaration section
List returnList = []
int totalProjectCount = 0 //variable to hold total no of projects value
int activeProjectCount = 0 //variable to hold total active projects value
int completedProjectCount = 0 //variable to hold total completed projects value
int userCount = 0 //variable to hold total active user count
String userAPIKey = apiKey //user API key for authorization
String method = 'GET' //method of request
String totalProjectURL = "https://"+ companyName + ".teamwork.com/projects.json?status=ALL" // Url to access All projects
StringBuilder out = getConnection(totalProjectURL, method, userAPIKey) //String builder to hold result
//catching result into json
JSONObject object = new JSONObject(out.toString()) //JSON object to store String in json format
totalProjectCount = object.projects.length()
String activeProjectCountURL = "https://"+ companyName + ".teamwork.com/projects.json?status=ACTIVE" // Url to access Active projects
out = getConnection(activeProjectCountURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
activeProjectCount = object.projects.length()
String completedProjectCountURL = "https://"+ companyName + ".teamwork.com/projects.json?status=COMPLETED" // Url to access completed projects
out = getConnection(completedProjectCountURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
completedProjectCount = object.projects.length()
String peopleURL = "https://"+ companyName + ".teamwork.com/people.json" // Url to access total active users
out = getConnection(peopleURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
userCount = object.people.length()
Map returnMap = [:]
returnMap.put('totalProjectCount', totalProjectCount)
returnMap.put('activeProjectCount', activeProjectCount)
returnMap.put('completedProjectCount', completedProjectCount)
returnMap.put('userCount', userCount)
addCount(returnMap, 'curo', 'countDetails')
println('project count successfully saved.')
}
function to add countDetails to mongo
def addCount(Map userMap, String dbName, String collectionName) {
try {
DB db = mongo.getDB(dbName)
DBCollection table = db.getCollection(collectionName)
table.insert(userMap as BasicDBObject)
def srvcResponseObj = [ responseStatus : "pass", responseCode : 200 ]
return srvcResponseObj
}
catch (Exception e)
{
println "Exception related to Mongo add record"
e.printStackTrace()
def srvcResponseObj = [ responseStatus : "fail", responseCode: 400 ]
return srvcResponseObj
}
}
function to fetch data from mongo
def fetchCountDetails(String databaseName, String collectionName) {
println 'inside fetch count details'
try {
DB db = mongo.getDB(databaseName)
DBCollection table = db.getCollection(collectionName)
DBCursor cursor = table.find()
Map returnCountMap = [:]
List temp = []
int cursorCounter = 0
while(cursor.hasNext()) {
Map temporaryMap = [:]
BasicDBObject doc = (BasicDBObject) cursor.next()
doc.remove('_id')
temp.add(doc)
cursorCounter++
}
returnCountMap.put('totalProjectCount', temp.totalProjectCount.sum())
returnCountMap.put('activeProjectCount',temp.activeProjectCount.sum())
returnCountMap.put('completedProjectCount',temp.completedProjectCount.sum())
returnCountMap.put('userCount',temp.userCount.sum())
if(cursorCounter>1)
println "Multiple objects found for eventID"
if(cursorCounter==0)
println "No objects found for eventID"
return returnCountMap
}
catch (Exception e)
{
println "Exception related to Mongo >> fetchUserDetails"
e.printStackTrace()
def srvcResponseObj = [ responseStatus : "fail", responseCode: 400 ]
return srvcResponseObj
}
}
now i am making request to REST api after fixed amount of interval and my response gets changed in terms of values, but if i call the add function again and again my documents get duplicated in mongodb and my expected result is that my new values gets reflected in mongodb

Is there a good string pluralization library for actionscript?

I haven't found a good library actionscript library for this yet.
I want to do things like:
Inflection.pluralize( "cat" ) == "cats"
Inflection.pluralize( "fish" ) == "fish"
I know ruby on rails has a library like this build in; and javascript has a really nice one as well: http://code.google.com/p/inflection-js/.
Any one know of a similar thing for actionscript?
Google says:
http://kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/
package
{
public class Inflect
{
private static var plural : Array = [
[/(quiz)$/i, "$1zes"],
[/^(ox)$/i, "$1en"],
[/([m|l])ouse$/i, "$1ice"],
[/(matr|vert|ind)ix|ex$/i, "$1ices"],
[/(x|ch|ss|sh)$/i, "$1es"],
[/([^aeiouy]|qu)y$/i, "$1ies"],
[/(hive)$/i, "$1s"],
[/(?:([^f])fe|([lr])f)$/i, "$1$2ves"],
[/(shea|lea|loa|thie)f$/i, "$1ves"],
[/sis$/i, "ses"],
[/([ti])um$/i, "$1a"],
[/(tomat|potat|ech|her|vet)o$/i, "$1oes"],
[/(bu)s$/i, "$1ses"],
[/(alias|status)$/i, "$1es"],
[/(octop)us$/i, "$1i"],
[/(ax|test)is$/i, "$1es"],
[/(us)$/i, "$1es"],
[/s$/i, "s"],
[/$/i, "s"]
];
private static var singular : Array = [
[/(quiz)zes$/i, "$1"],
[/(matr)ices$/i, "$1ix"],
[/(vert|ind)ices$/i, "$1ex"],
[/^(ox)en$/i, "$1"],
[/(alias|status)es$/i, "$1"],
[/(octop|vir)i$/i, "$1us"],
[/(cris|ax|test)es$/i, "$1is"],
[/(shoe)s$/i, "$1"],
[/(o)es$/i, "$1"],
[/(bus)es$/i, "$1"],
[/([m|l])ice$/i, "$1ouse"],
[/(x|ch|ss|sh)es$/i, "$1"],
[/(m)ovies$/i, "$1ovie"],
[/(s)eries$/i, "$1eries"],
[/([^aeiouy]|qu)ies$/i, "$1y"],
[/([lr])ves$/i, "$1f"],
[/(tive)s$/i, "$1"],
[/(hive)s$/i, "$1"],
[/(li|wi|kni)ves$/i, "$1fe"],
[/(shea|loa|lea|thie)ves$/i,"$1f"],
[/(^analy)ses$/i, "$1sis"],
[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, "$1$2sis"],
[/([ti])a$/i, "$1um"],
[/(n)ews$/i, "$1ews"],
[/(h|bl)ouses$/i, "$1ouse"],
[/(corpse)s$/i, "$1"],
[/(us)es$/i, "$1"],
[/s$/i, ""]
];
private static var irregular : Array = [
['move' , 'moves'],
['foot' , 'feet'],
['goose' , 'geese'],
['sex' , 'sexes'],
['child' , 'children'],
['man' , 'men'],
['tooth' , 'teeth'],
['person' , 'people']
];
private static var uncountable : Array = [
'sheep',
'fish',
'deer',
'series',
'species',
'money',
'rice',
'information',
'equipment'
];
public static function pluralize( string : String ) : String
{
var pattern : RegExp;
var result : String;
// save some time in the case that singular and plural are the same
if (uncountable.indexOf(string.toLowerCase()) != -1)
return string;
// check for irregular singular forms
var item : Array;
for each ( item in irregular )
{
pattern = new RegExp(item[0] + "$", "i");
result = item[1];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
// check for matches using regular expressions
for each ( item in plural)
{
pattern = item[0];
result = item[1];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
return string;
}
public static function singularize( string : String ) : String
{
var pattern : RegExp;
var result : String
// save some time in the case that singular and plural are the same
if (uncountable.indexOf(string.toLowerCase()) != -1)
return string;
// check for irregular singular forms
var item : Array;
for each ( item in irregular )
{
pattern = new RegExp(item[1] + "$", "i");
result = item[0];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
// check for matches using regular expressions
for each ( item in singular)
{
pattern = item[0];
result = item[1];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
return string;
}
public static function pluralizeIf(count : int, string : String) : String
{
if (count == 1)
return "1 " + string;
else
return count.toString() + " " + pluralize(string);
}
}
}