fork download
  1. importPackage(java.io)
  2. importPackage(java.lang)
  3.  
  4. // Reverse a calculation procedure involving different kinds of price increase
  5.  
  6. // Increase by percent
  7. function proz(p) {
  8. return function(x) {
  9. return x*(1+p/100)
  10. }
  11. }
  12.  
  13. // Increase by absolute value
  14. function abs(q) {
  15. var f = function(x) {
  16. return x+q
  17. }
  18. f.isAbsolute = true
  19. return f
  20. }
  21.  
  22. // Increase by percent of the calculation base
  23. function proz_base(p) {
  24. return function(x,base) {
  25. return x+base*p/100
  26. }
  27. }
  28.  
  29. function schema( ) {
  30. var conditions = convertToArray( arguments );
  31. return {
  32. // "compute" applies the schema to a base price
  33. compute:compute,
  34. // "resolve" finds the base price yielding the specified result
  35. resolve:function(result) {
  36. return ( result - compute(0) ) / reducedSchema().compute(1)
  37. }
  38. }
  39.  
  40. function compute(base) {
  41. return conditions.reduce( function(result,cond) {
  42. return cond(result,base)
  43. },
  44. base )
  45. }
  46.  
  47. function reducedSchema() {
  48. return schema.apply( null, conditions.filter( isRelative ) )
  49. }
  50.  
  51. function isRelative( cond ) {
  52. return ! cond.isAbsolute
  53. }
  54.  
  55. }
  56.  
  57. function convertToArray( arraylikeThing ) {
  58. return Array.prototype.slice.apply( arraylikeThing )
  59. }
  60.  
  61.  
  62. // Test
  63. var s = schema(
  64. proz( 7 ),
  65. abs(5),
  66. proz_base(10),
  67. abs(3),
  68. proz(13)
  69. )
  70.  
  71. System.out.println( s.compute( s.resolve( 20 ) ) )
Success #stdin #stdout 0.44s 381888KB
stdin
Standard input is empty
stdout
20.0